Constructor Injection with Collection Example in Spring

We can inject collection values by constructor in spring structure. There can be utilized three components inside the constructor-arg component. It can be:

  1. list
  2. set
  3. map

Every accumulation can have string based and non-string based qualities.

In this sample, we are taking the case of Forum where One inquiry can have different answers. There are three pages:

  2. applicationContext.xml

In this example, we are using list that can have duplicate elements, you may 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<String> answers;

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

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



The list element of constructor-arg is used here to define the list.

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

<bean id="q" class="com.javatportal.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<value>Java is a programming language</value>
<value>Java is a Platform</value>
<value>Java is an Island of Indonasia</value>


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