Constructor Injection With String Collection


In the String collection-based Constructor Dependency injection of the Spring framework, we will inject a Collection of String to an object instead of one string value. In such a way, we inject a Collection of strings through a constructor. Each collection can have the values of a string and non-string type.

In a constructor-arg element, we can use three elements that are list, set, map. But most of the time, we are required to use the list element.

In this guide, we will study an example of a Forum where there exists one question and its many answers. We will be required to use three pages that are listed below to accomplish this task.

  • Question.java
  • applicationContext.xml
  • Test.java

Here, in this example, we are using a list element that can be duplicated in numbers. Here we can use ‘Set’ that has unique elements But, you will be required to convert the list to set in the applicationContext.xml file as well as in the Question.java file.


This class includes three properties, 2 constructors, and one displayInfo() method to display the information. Here, a list will be used to contain 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;  

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

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




This class includes a list element of the constructor-arg to define the list.

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


<bean id="q" class="com.intellinuts.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 the Island of Indonesia</value>  



This class receives the bean from the applicationContext.xml file and calls the displayInfo () method to display the output.

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



The output will be seen as below:

Java is a programming language

Java is a Platform

Java is the Island of Indonesia