Sometimes, it is necessary to inject a Collection of type
into a bean using Spring injection. e.g. A Team may contains a Set of Players.
This is achieved by using the
tag within the
tag in Spring configuration.
The following sample program provides an overview of injecting a Set of players into a Team bean.
Sample Program Overview
We will create a Team class.
We will also create a member of Team class called ‘players’ of type
Using Spring’s configuration, we will inject some values into the players set (e.g. ‘Alba’, ‘Bach’ and ‘Cindy’)
Finally, we will test our setup using TestInjectionSet class which will load Spring context and get a reference to Team class. We will fetch the players from Team class and print them in the console to verify that the set of players has been successfully injected.
- Although we have used setter injection in this example, it is also possible to inject java.util.Set using constructor injection.
- Although we used simple types within the list using value tag, we can also use bean references within list using ref tag.
Create the Team class (see below).
Create a member called ‘players’ of type
(see line 7 below)
Create accessor methods for ‘players’ (see lines 9-15 below)
Create the spring-config.xml file (see below).
Declare bean for Team class (see line 10 below)
For the ‘players’ property (see line 11 below), we define a
tag (see line 12 below).
We populate the set using the
tag (see lines 13-15 below).
Finally, we need a java program to test the our setup.This is done by TestInjectionSet.java (see source code below).
We need to tell Spring framework to use the ‘spring-config.xml’ to load our beans (see line 11 below).
We get the reference to Team class through Spring using the bean name ‘team’ (see line 12 below).
We access the Team.getPlayers() method and output the contents to verify that the Set has been injected successfully (see line 13 below).
This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies) on your machine and automatically run the program for you as shown in the steps below. To run the sample program, you only need Java Runtime Environment (JRE) on your machine and nothing else.
(Alternatively you can go the folder containing the springinjectionset-installer.jar and execute the jar using
java -jar springinjectionset-installer.jar
This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called
. All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.