Setter Injection with Collection Example in Spring

We can infuse accumulation values by setter system in spring structure. There can be utilized three components inside the property component.

  • list
  • set
  • map

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

Question.java

This class contains three properties with setters and getters and displayInfo() strategy that prints the data. Here, we are utilizing List to contain the numerous 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;

//setters and getters

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

}
applicationContext.xml

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

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="q" class="com.javatportal.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<list>
<value>Java is a programming language</value>
<value>Java is a platform</value>
<value>Java is an Island</value>
</list>
</property>
</bean>

</beans>
Test.java

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;
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");
	q.displayInfo();
	
}
}