Introduction
So far we have covered the setting of the expectations of the classes using constructor injection or the setter injections, and we saw how we can set a single bean expectation. What if you want to inject a dependency which is a collection? Well, Java Spring lets you do that with collection elements of Spring:
- <list> : Helps you setup injection of list of values, allowing duplication of values
- <set> : Helps you setup injection of set of values, ensuring distinct (i.e. no duplication) values
- <map> : Helps you setup injection of name-value pairs, name and value can be of any type.
- <props> : Helps you setup injection of name-value pairs, name and value both should be of type String only.
In our "Popular Talent Show" we have a performer who can play more than one instrument at the same time so let us see how we can implement this:
- public class BandMan implements Performer
- {
- private Collection < Instrument > _instrumentList;
- public void Initialize()
- {
- System.out.println("One Man Band: Registering in the show.");
- }
- public void Destroy()
- {
- System.out.println("One Man Band: Signing off from the show.");
- }
- @Override
- public void Perform() throws PerformaceException
- {
- for (Instrument instrument: _instrumentList)
- {
- instrument.Play();
- }
- }
- public void setInstruments(Collection < Instrument > instrumentList)
- {
- _instrumentList = instrumentList;
- }
- }
We have created a new class which would represent our one-man-band army. It has nothing special, just a collection set using the setter method, and in the interface implementation, we iterate over the available instruments and invoke the play method on it.
Now our performer would need multiple instruments to play at the same time, so let us go ahead and create a "Flute" instrument for our performer using the "Drum" instrument that is already available:
- public class Flute implements Instrument
- {
- @Override
- public void Play() {
- System.out.println("Playing Flute : ....");
- }
- }


Join the conversation! Your thoughts help the community grow.