img
For annotation-style Construction Injection, the confusion can be avoided by applying the
annotation directly to the target constructor method, as we've done in Listing 4-34.
Listing 4-34. Constructor Confusion (Annotation)
package com.apress.prospring3.ch4.annotation;
// Codes omitted
@Service("constructorConfusion")
public class ConstructorConfusion {
private String someValue;
public ConstructorConfusion(String someValue) {
System.out.println("ConstructorConfusion(String) called");
this.someValue = someValue;
}
@Autowired
public ConstructorConfusion(@Value("90") int someValue) {
System.out.println("ConstructorConfusion(int) called");
this.someValue = "Number: " + Integer.toString(someValue);
}
// Codes omitted
}
By applying the @Autowired annotation to the desired constructor method, Spring will use that
method to instantiate the bean and inject the value as specified. Like before, you should externalize the
value into the configuration.
Note You can apply the @Autowired annotation to only one of the constructor methods. If you apply the anno-
tation to more than one constructor method, Spring will complain during bootstrapping the ApplicationContext.
Injection Parameters
In the two previous examples, you saw how to inject other components and values into a bean using
both Setter Injection and Constructor Injection. Spring supports a myriad of options for injection
parameters, allowing you to inject not only other components and simple values but also Java
Collections, externally defined properties, and even beans in another factory. You can use all of these
injection parameter types for both Setter Injection and Constructor Injection by using the corresponding
tag under the <property> and <constructor-args> tags, respectively.
Injecting Simple Values
Injecting simple values into your beans is easy. To do so, simply specify the value in the configuration
tag, wrapped inside a <value> tag. By default, not only can the <value> tag read String values, but it can
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home