Spring Map Example


 

Spring Map Example

In this tutorial you will see an example of implement map in spring.

In this tutorial you will see an example of implement map in spring.

Spring Map Example

In this example you will see how bean is prepared for injecting Map collection type key and its values.

MapBean.java

package spring.map.example;

import java.util.Iterator;
import java.util.Map;

public class MapBean {
  private Map<String, Integer> student;
  public void setDetails(Map<String, Integer> student) {
  this.student = student;
  }
  public void showDetails() {
     Iterator it = student.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry)it.next();
            System.out.println(pairs.getKey() " = " + pairs.getValue());
        }
  }
}

MapBeanMain.java

package spring.map.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MapBeanMain {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
        "context.xml");
    MapBean bean = (MapBeanbeanfactory.getBean("mapbean");
    bean.showDetails();
  }
}

context.xml

<bean id="mapbean" class="spring.map.example.MapBean">
     <property name="details">
          <map>
               <entry key="Satya" value="101"/>
               <entry key="Rohit" value="102"/>
               <entry key="Aniket" value="103"/>
          </map>
     </property>
</bean>

When you run this application it will display output as shown below:

Satya = 101

Rohit = 102

Aniket = 103

Download this example code

Ads