Spring Setter Injection with Collection

Spring Framework provides following elements to inject collection values inside <property> element.

  • list
  • map
  • set

Collection elements can be primitive or object collections.Here I am taking example of Question class which has multiple answers.

Question.java

Question class has collection of String for multiple answers.

package com.startwithjava;
import java.util.List;
public class Question {
	private int id;
	private String question;
	private List<String> answers;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getQuestion() {
		return question;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public List<String> getAnswers() {
		return answers;
	}
	public void setAnswers(List<String> answers) {
		this.answers = answers;
	}

}

applicationContext.xml

This file contains bean entry for Question class.

<?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: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="question" class="com.startwithjava.Question">
  <property name="id" value="1" />
   <property name="question" value="What is Spring" />
 	<property name="answers">  
		<list>  
		<value>Spring is  Java Framework</value>  
		<value>Spring is a platform</value>  
		<value>Spring is an season</value>  
		</list>  
   </property>  
  </bean>
 </beans> 

Test.java

This file contains the code to obtain the object of Question from applicationContext.xml.

package com.startwithjava;
import java.util.List;

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); 
    Employee e1 = (Employee) factory.getBean("emp");
    e1.display();
    Customer c  = (Customer)factory.getBean("cust");
    c.display();
    
    //Setter Collection Injection
    
    Question q = (Question)factory.getBean("question");
    List<String> answers = q.getAnswers();
    System.out.println("Quesion:"+q.getQuestion());
    for(String ans:answers)
    	System.out.println("Answer:"+ans);
} 
} 

Leave a Reply