Setter Injection with Non-String Collection Example in Spring

In the event that we have ward object in the using so as to gather, we can infuse these data the ref component inside the rundown, set or guide.

Here, we will utilize rundown, set or guide component inside the property component. In this sample, we are taking the illustration of Forum where One inquiry can have numerous answers.

Be that as it may, Answer has its own particular data, for example, answerId, answer and postedBy. There are four pages utilized as a part of this case:

  3. applicationContext.xml

In this case, we are utilizing rundown that can have copy components, you may utilize set that have just one of a kind components. Be that as it may, you have to change rundown to set in the applicationContext.xml document and List to Set in the record.

This class contains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.

package com.javatportal;

import java.util.Iterator;
import java.util.List;

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

//setters and getters

public void displayInfo(){
	System.out.println(id+" "+name);
	System.out.println("answers are:");
	Iterator<Answer> itr=answers.iterator();


This class has three properties id, name and by with constructor and toString() method.

package com.javatportal;

public class Answer {
private int id;
private String name;
private String by;

//setters and getters

public String toString(){
	return id+" "+name+" "+by;


The ref element is used to define the reference of another bean. Here, we are using bean attribute of ref element to specify the reference of another bean.

<?xml version="1.0" encoding="UTF-8"?>

<bean id="answer1" class="com.javatportal.Answer">
<property name="id" value="1"></property>
<property name="name" value="Java is a programming language"></property>
<property name="by" value="Neha Singh Malik"></property>
<bean id="answer2" class="com.javatportal.Answer">
<property name="id" value="2"></property>
<property name="name" value="Java is a platform"></property>
<property name="by" value="Rahul"></property>

<bean id="q" class="com.javatportal.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<ref bean="answer1"/>
<ref bean="answer2"/>


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

package com.javatportal;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

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");