Tuesday, 28 February 2017

Spring: Inject Map

By using <map> element, you can inject map.

Example
 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="countries">
   <map>
    <entry key="Iceland" value="Reykjavik" />
    <entry key="India" value="New Delhi" />
    <entry key="Indonesia" value="Jakarta" />
    <entry key="Iran" value="Tehran" />
    <entry key="Iraq" value="Baghdad" />
   </map>
  </property>
 </bean>

Following is the complete working application.

Countries.java
package com.sample.pojo;

import java.util.Map;

public class Countries {
 private Map<String, String> countries;

 public Map<String, String> getCountries() {
  return countries;
 }

 public void setCountries(Map<String, String> countries) {
  this.countries = countries;
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="countries">
   <map>
    <entry key="Iceland" value="Reykjavik" />
    <entry key="India" value="New Delhi" />
    <entry key="Indonesia" value="Jakarta" />
    <entry key="Iran" value="Tehran" />
    <entry key="Iraq" value="Baghdad" />
   </map>
  </property>
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Countries;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Countries countries = context.getBean("demoCountryCapitals", Countries.class);

  Map<String, String> countriesMap = countries.getCountries();

  for (String country : countriesMap.keySet()) {
   System.out.println(country + " : " + countriesMap.get(country));
  }

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
Iceland : Reykjavik
India : New Delhi
Indonesia : Jakarta
Iran : Tehran
Iraq : Baghdad










Previous                                                 Next                                                 Home

No comments:

Post a Comment