logo

Spring Setter Injection With Collection


Show

In the Spring framework, we can also examine the dependency between the objects through the collection. In the property element, we can use three elements that are List, Set, and Map. Each collection can have either string and non-string-based values.

Here, we will take you to the example of a forum where One question can have several answers. For this purpose, we will use three pages that are Question.java, applicationContext.xml, and Test.java

Out of the three property elements that can be used, we choose to use a List that can have duplicate elements. You can also use Set that contains unique elements. But you need to change the list to set in the applicationContext.xml file and Question.java file.

Question.Java

This class contains three properties with setters and getters and displayInfo() method that gives the output information. Here the List element will be used to include the multiple answers.

package com.intellinuts;  
import java.util.Iterator;  
import java.util.List;    

public class Question {  
private int id;  
private String name;  
private List<String> answers;  

//setters and getters  
public void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println("answers are:");  
    Iterator<String> itr=answers.iterator();  
    while(itr.hasNext()){  
       System.out.println(itr.next());  
    }  
}  

}  

ApplicationContext.xml

Here, the list is defined by the list element of constructor-arg.

  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="q" class="com.intellinuts.Question">  
<property name="id" value="1"></property>  
<property name="name" value="What is Java?"></property>  
<property name="answers">  
<list>  
<value>Java is a programming language</value>  
<value>Java is a platform</value>  
<value>Java is an Island</value>  
</list>  
</property>  
</bean>  

</beans>

Test.Java

This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.

package com.intellinuts;  

import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  

public class Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);      

    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  

}  

}