Constructor Injection with Non-String Collection Example in Spring

In case we have a dependent object in the collection then it is possible to inject these information with the help of ref element which is present in the list, set or the map.

Here we will understand the sample of one question having multiple answers. In this case the answer has its own fields like the answer itself, answerId and postedBy details.

There are basically four pages which will be included namely .

  3. applicationContext.xml

This is a list which has multiple and duplicate use set that have only unique elements. but you need to change list to set in the applicationContext.xml file and List to Set in the file.

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;

public Question() {}
public Question(int id, String name, List<Answer> answers) {
	super(); = id; = name;
	this.answers = answers;

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;

public Answer() {}
public Answer(int id, String name, String by) {
	super(); = id; = name; = by;

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="ans1" class="com.javatportal.Answer">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Java is a programming language"></constructor-arg>
<constructor-arg value="John"></constructor-arg>

<bean id="ans2" class="com.javatportal.Answer">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Java is a Platform"></constructor-arg>
<constructor-arg value="Ravi"></constructor-arg>

<bean id="q" class="com.javatportal.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<ref bean="ans1"/>
<ref bean="ans2"/>


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