In the
previous chapters, we saw how to perform constructor injections. Next, we will cover how to perform setter injections using the Spring framework. This is another way of resolving dependencies in your class; let's see it using a use case of how one can leverage this.
In our Popular Talent Show we have a new performer, Shaun, who can play any sort of instrument, so to represent that, let's write a generic instrument interface:
- public interface Instrument
- {
- void Play();
- }
Next, we need a class to represent our performer:
- public class Percussionist implements Performer
- {
- private Instrument _instrument;
- @Override
- public void Perform() throws PerformaceException
- {
-
- _instrument.Play();
- }
- public void setInstrument(Instrument instrument)
- {
- _instrument = instrument;
- }
- }
The class represents a percussionist who plays the instrument injected to it from the setter method; well all looks good but we need the instrument which Shaun would be playing:
- public class Drums implements Instrument
- {
- @Override
- public void Play()
- {
-
- System.out.println("Playing Drums : ....");
- }
- }
As you can see we have drums which implement the instrument interface and we need this set up in the bean configuration file, so the Spring framework can identify it:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <bean id="mike" class="spring.decoded.big.awards.Juggler">
- <constructor-arg value="10" />
- </bean>
-
- <bean id="bestOfMe" class="spring.decoded.big.awards.Singer" />
- <bean id="john" class="spring.decoded.big.awards.SingingJuggler">
- <constructor-arg value="11" />
- <constructor-arg ref="bestOfMe"/>
- </bean>
- <bean id="drum" class="spring.decoded.big.awards.Drums" />
- <bean id="shaun" class="spring.decoded.big.awards.Percussionist">
- <property name="instrument" ref="drum" />
- </bean>
- <bean id="bigAwardsStage"
- class="spring.decoded.big.awards.Stage"
- factory-method="getIstance" />
- </beans>
Notice that we have declared the percussionist too in the bean file, and instead of a constructor-arg attribute we have a property attribute to inject the dependency, what that bean declaration says is that:
"For the property whose name is an instrument in the class Percussionist, set it with a reference drum declared in the bean configuration file above". Well, all we need now is to get the instance of this class and invoke the right method which is performed in this case to set the show on fire: In our PopularTalentShow.java class get these lines: