In this tutorial you will learn about how to wire Map Collection in Spring framework
In this tutorial you will learn about how to wire Map Collection in Spring frameworkThe <map> element is used to store values in key and value pair i.e. values of type java.util.Map. Its sub element <entry> defines a member of the Map.
Lets take an example to demonstrate how map element is used.
Article.java: The Article class contains two types of properties named title and authorsInfo. The property title is of String type and authorsInfo is of Map type.
import java.util.*;
public class Article
{
private String title;
private Map<String, String> authorsInfo;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthorsInfo(Map<String, String> authorsInfo) {
this.authorsInfo = authorsInfo;
}
public Map<String, String> getAuthorsInfo() {
return authorsInfo;
}
}
spring-beans.xml: The <map> element is used to provide values to the Map type property of the Article class. Here <entry> element provides those values using key and value attributes.
<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-2.5.xsd">
<bean id="article" class="Article">
<property name="title" value="RoseIndia"/>
<property name="authorsInfo">
<map>
<entry key="1" value="Deepak" />
<entry key="2" value="Arun"/>
<entry key="3" value="Vijay" />
</map>
</property>
</bean>
</beans>
AppMain.java: This class loads the context configuration file spring-beans-list.xml from the class path.
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.*;
public class AppMain
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"spring-beans.xml"});
Article article = (Article)appContext.getBean("article");
System.out.println("Article Title: "+article.getTitle());
Map<String, String> authorsInfo = article.getAuthorsInfo();
System.out.println("Article Author: ");
for (String key : authorsInfo.keySet()) {
System.out.println(key + " : "+(String)authorsInfo.get(key));
}
}
}
The output of the above program will be as below:
Article
Title: RoseIndia
Article Author:
1 : Deepak
2 : Arun
3 : Vijay