
Spring Constructor Injection with collection
The Spring, constructor injection with collections allows you to inject collections (e.g., lists, sets, maps) of objects into a bean’s constructor. This is useful when a bean needs to work with multiple instances of a particular type or when you want to configure a bean with a collection of values. Here’s how to perform constructor injection with a collection in Spring:
1. Create Dependent Objects:
First, create the dependent objects (beans) that you want to inject into another bean’s constructor. These objects can be of any type, and they should be defined as separate Spring beans. For this example, let’s create a Person
class:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
// Getter and setter for 'name'
}
2. Configure Beans in XML:
In your Spring configuration file (e.g., applicationContext.xml
), define the beans and specify the constructor injection by providing the constructor arguments as a collection. You can use <list>
, <set>
, or <map>
elements, depending on the type of collection you want to inject.
In this example, we’ll use a <list>
to inject a list of Person
objects into another bean’s constructor:
<bean id="john" class="com.example.Person">
<constructor-arg value="John" />
</bean>
<bean id="alice" class="com.example.Person">
<constructor-arg value="Alice" />
</bean>
<bean id="team" class="com.example.Team">
<constructor-arg>
<list>
<ref bean="john" />
<ref bean="alice" />
</list>
</constructor-arg>
</bean>
In this XML configuration:
- We define “john” and “alice” beans of class
com.example.Person
with different names. - We define a “team” bean of class
com.example.Team
and inject a list of “john” and “alice” beans as a constructor argument.
3. Create the Bean Receiving the Collection:
Now, create the bean that will receive the collection as a constructor argument. In this example, we’ll create a Team
class that receives a list of Person
objects:
import java.util.List;
public class Team {
private List<Person> members;
public Team(List<Person> members) {
this.members = members;
}
// Getter and setter for 'members'
}
4. Access the Target Bean:
You can access the target bean, “team,” by retrieving it from the Spring application context. The list of “john” and “alice” beans will be injected into the Team
bean’s constructor when it is created.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Team team = context.getBean("team", Team.class);
// Use the 'team' bean, which now has a list of 'Person' members
Constructor injection with collections allows you to pass multiple instances of objects to a bean’s constructor, making it suitable for scenarios where you need to configure a bean with a group of related dependencies. You can use the appropriate collection type (<list>
, <set>
, <map>
, etc.) based on your specific requirements.