Spring Collection (List, Set and Map) Dependency Injection Example


On this page, we will show you how to inject the collections (List, Set, and Map) type values to the bean class using XML file. Spring framework supports 4 major type collection.

  • List
  • Set
  • Map and
  • Properties (discuss in next tutorial)- Check now

We can inject the values for both type setter and constructor based dependency injection. In my example, I have mostly used the setter-based dependency injection.

To inject the List type values we have <list/> subelement, for Set type we have <set/> subelement and for Map types <map/> subelement of <property/> tag.

Above configuration works fine if your reference type is an Interface. But if you want to inject the required type collection it will not work. To resolve this type of problem, it may further be divided into two parts.

  1. Default Type Collection Dependency Injection
  2. Required Type Collection Dependency Injection

Note: DTD or XSD based configuration works fine for default type collection DI but required type collection DI will not work with DTD, you must go with XSD based configuration.

DTD based configuration.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!--mapping of class-->
</beans>

XSD based configuration.

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

1- Default Type Collection Dependency Injection

If the reference type is an Interface, then spring framework will prepare ArrayList object for <list/> tag, LinkedHashSet object for <set/> tag and for <map/> tag it will use LinkedHashMap object by default.

1.1 Spring Beans

Create a DefaultType class which have three Interface reference type collection object and generate its setter method and a business logic that actually uses the injected collection values.

DefaultType.java
package org.websparrow.beans;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultType {

	// Generate setters...
	private List<String> fruits;
	private Set<String> cricketers;
	private Map<String, String> countryCapital;

	public void setFruits(List<String> fruits) {
		this.fruits = fruits;
	}

	public void setCricketers(Set<String> cricketers) {
		this.cricketers = cricketers;
	}

	public void setCountryCapital(Map<String, String> countryCapital) {
		this.countryCapital = countryCapital;
	}

	// business logic that uses the injected values...
	public void display() {

		System.out.println("Fruits...." + "");

		for (String fruit : fruits) {
			System.out.println(fruit);
		}

		System.out.println("\nCricketers...." + "");

		for (String cricketer : cricketers) {
			System.out.println(cricketer);
		}

		System.out.println("\nCountry and Capital...." + "");

		Set<String> keys = countryCapital.keySet();
		for (String key : keys) {
			System.out.println(key + " : " + countryCapital.get(key));
		}
	}
}

1.2 Spring Beans Configuration

See different code snippets to declare collection in bean configuration file.

1.2.1 List type

To inject the List values we can use <list/> tag and its child tag <value/> to pass the value.

<property name="fruits">
    <list>
        <value>Apple</value>
        <value>Mango</value>
    </list>
</property>

1.2.2 Set type

For Set we have <set/> tag and its child tag <value/> to pass the value. In the Set tag duplicate values are not allowed.

<property name="cricketers">			
    <set>
        <value>Sachin</value>
        <value>Virat</value>
        <value>Sehwag</value>
    </set>
</property>

1.2.3 Map type

And for Map we have <map/> tag and its child tag <entry/> to pass the values in pair of key and value. Map will also not accept the duplicate values.

<property name="countryCapital">
    <map>
        <entry key="India" value="New Delhi" />
        <entry key="Russia" value="Moscow" />
        <entry key="France" value="Paris" />
    </map>
</property>

Check full Spring bean configuration file.

default.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="def" class="org.websparrow.beans.DefaultType">
        <!--java.util.List-->
        <property name="fruits">
            <list>
                <value>Apple</value>
                <value>Mango</value>
            </list>
        </property>
        <!--java.util.Set-->
        <property name="cricketers">
            <set>
                <value>Sachin</value>
                <value>Virat</value>
                <value>Sehwag</value>
            </set>
        </property>
        <!--java.util.Map-->
        <property name="countryCapital">
            <map>
                <entry key="India" value="New Delhi" />
                <entry key="Russia" value="Moscow" />
                <entry key="France" value="Paris" />
            </map>
        </property>
    </bean>
</beans>

1.3 Execution

Create a DefaultClient class, load the default configuration file and run it.

DefaultClient.java
package org.websparrow.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.websparrow.beans.DefaultType;

public class DefaultClient {
	public static void main(String[] args) {

		ApplicationContext ap = new ClassPathXmlApplicationContext("default.xml");

		DefaultType def = (DefaultType) ap.getBean("def");
		def.display();
	}
}

1.4 Output

You will get the following result on your console log.

Fruits....
Apple
Mango

Cricketers....
Sachin
Virat
Sehwag

Country and Capital....
India : New Delhi
Russia : Moscow
France : Paris

2- Required Type Collection Dependency Injection

For specific required type collection dependency injection, you must need to use the XSD based configuration and define util schema. In this example, I have used Vector, TreeSet and Hashtable for the required type collection DI.

2.1 Spring Beans

Create a RequiredType class which have the required type collection object. Generate its setter method.

RequiredType.java
package org.websparrow.beans;

import java.util.Hashtable;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;

public class RequiredType {

	// Generate setters...
	private Vector<String> empName;
	private TreeSet<String> empId;
	private Hashtable<String, String> empIdName;

	public void setEmpName(Vector<String> empName) {
		this.empName = empName;
	}

	public void setEmpId(TreeSet<String> empId) {
		this.empId = empId;
	}

	public void setEmpIdName(Hashtable<String, String> empIdName) {
		this.empIdName = empIdName;
	}

	// business logic
	public void display() {

		System.out.println("Name......" + "");

		for (String name : empName) {
			System.out.println(name);
		}

		System.out.println("\nIds......" + "");

		for (String id : empId) {
			System.out.println(id);
		}

		System.out.println("\nId and Name...." + "");

		Set<String> set = empIdName.keySet();
		for (String idName : set) {
			System.out.println(idName + " : " + empIdName.get(idName));
		}
	}
}

2.2 Spring Beans Configuration

See the different code snippets to declare the required type collection in bean configuration file.

2.2.1 Vector type

To inject the values for Vector, we have <util:list list-class="java.util.Vector"/> child tag of <property/> element.

<property name="empName">
    <util:list list-class="java.util.Vector">
        <value>Atul</value>
        <value>Sandeep</value>
    </util:list>
</property>

2.2.2 TreeSet type

For TreeSet we can use the <util:set set-class="java.util.TreeSet"/>. It will also not accept the duplicate values.

<property name="empId">
    <util:set set-class="java.util.TreeSet">
        <value>WSO1101</value>
        <value>WSO1201</value>
    </util:set>
</property>

2.2.3 Hashtable type

And for Hashtable we have <util:map map-class="java.util.Hashtable"/> tag and its child tag <entry/> to pass the values in the pair of key and value. Hashtable will also not accept the duplicate values.

<property name="empIdName">
    <util:map map-class="java.util.Hashtable">
        <entry key="WSO1" value="Vipul" />
        <entry key="WSO2" value="Mukul" />
        <entry key="WSO3" value="Ankita" />
    </util:map>
</property>

Check full Spring bean configuration file for required type collection DI.

required.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" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="req" class="org.websparrow.beans.RequiredType">
        
        <property name="empName">
            <util:list list-class="java.util.Vector">
                <value>Atul</value>
                <value>Sandeep</value>
            </util:list>
        </property>

        <property name="empId">
            <util:set set-class="java.util.TreeSet">
                <value>WSO1101</value>
                <value>WSO1201</value>
            </util:set>
        </property>

        <property name="empIdName">
            <util:map map-class="java.util.Hashtable">
                <entry key="WSO1" value="Vipul" />
                <entry key="WSO2" value="Mukul" />
                <entry key="WSO3" value="Ankita" />
            </util:map>
        </property>

    </bean>
</beans>

2.3 Execution

Create a RequiredClient class, load the required configuration file and run it.

RequiredClient.java
package org.websparrow.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.websparrow.beans.RequiredType;

public class RequiredClient {
	public static void main(String[] args) {

		ApplicationContext ap = new ClassPathXmlApplicationContext("required.xml");

		RequiredType adv = (RequiredType) ap.getBean("req");
		adv.display();
	}
}

2.4 Output

You will get the following result on your console log.

Name......
Atul
Sandeep

Ids......
WSO1101
WSO1201

Id and Name....
WSO3 : Ankita
WSO2 : Mukul
WSO1 : Vipul

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.