Javatpoint Logo
Javatpoint Logo

Constructor Injection with Collection Example

We can inject collection values by constructor in spring framework. There can be used three elements inside the constructor-arg element.

It can be:
  1. list
  2. set
  3. map
Each collection can have string based and non-string based values.

In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages:

  1. Question.java
  2. applicationContext.xml
  3. Test.java

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 Question.java file.

Question.java

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

applicationContext.xml

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

Test.java

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





Please Share

facebook twitter google plus pinterest tumbler

Learn Latest Tutorials