CHAPTER 5: Building Java Web Applications with Spring Web MVC 209
Listing 5-4. Configuring Dependency
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
- public class ClassA{
- private ClassB classB;
- // a setter method to inject the dependency.
- public void setClassB(ClassB classB) {
- this.classB = classB;
- }
- // a getter method to return classB
- public ClassB getClassB() {
- return classB;
- }
- }
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.