Java Reference
In-Depth Information
Listing 5-4. Configuring Dependency
1. <!-- Definition for classA bean -->
2. <bean id="classA" class="ClassA">
3. <constructor-arg ref="classB"/>
4. </bean>
5.
6. <!-- Definition for classB bean -->
7. <bean id="classB" class="ClassB">
8. </bean>
Line 2
: This specifies the
classA
bean to be created and managed by the Spring
container.
Line 3
:
<constructor-arg>
configures bean properties via constructor injection
by declaring them in the elements.
Line 7
: This specifies that
classB
bean should be created and managed by the
Spring container.
The dependency injection depicted in Listing 5-4 is called
constructor
-based dependency injection.
Constructor-based DI is accomplished when the container invokes a class constructor with a
number of arguments, each representing a dependency on another class. There is another variant of
DI called
setter
-based dependency injection. In setter-based DI, the container, after invoking a no-
argument constructor or no-argument static factory method to instantiate your bean, calls the setter
methods on your beans. To use setter-based DI, you need to modify Listing 5-2 to look like Listing 5-5.
Listing 5-5. Setter Method to Inject Dependency
1. public class ClassA{
2. private ClassB classB;
3.
4. // a setter method to inject the dependency.
5. public void setClassB(ClassB classB) {
6. this.classB = classB;
7. }
8. // a getter method to return classB
9. public ClassB getClassB() {
10. return classB;
11. }
12.
13. }
In Listing 5-5, the DI takes place through setter methods of the
ClassA
class in which the
ClassB
instance is created, and this instance is used to call setter methods to initialize
ClassA
's properties.
Listing 5-6 illustrates the bean definition that should be included in the configuration metadata file
illustrated in Listing 5-3 to achieve the setter-based dependency injection required in Listing 5-5.