<value>This is a configurable message</value>
</constructor-arg>
</bean>
In this code, instead of using a <property> tag, we used a <constructor-arg> tag. Because we are not
passing in another bean this time, just a String literal, we use the <value> tag instead of the <ref> to
specify the value for the constructor argument.
When you have more than one constructor argument or your class has more than one constructor,
you need to give each <constructor-arg> tag an index attribute to specify the index of the argument,
starting at 0, in the constructor signature. It is always best to use the index attribute whenever you are
dealing with constructors that have multiple arguments to avoid confusion between the parameters and
ensure that Spring picks the correct constructor.
Like the p namespace, in Spring 3.1, you can also use the c namespace, as shown here:
<bean id="messageProvider"
class="com.apress.prospring3.ch4.xml.ConfigurableMessageProvider"
c:message="This is a configurable message"/>
To use an annotation for Constructor Injection, we also use the @Autowired annotation in the target
bean's constructor method, as shown in Listing 4-28, which is an alternative option to the one using
Setter Injection, as shown in Listing 4-24.
Listing 4-28. Using Constructor Injection (Annotation)
package com.apress.prospring3.ch4.annotation;
import org.springframework.beans.factory.annotation.Value;
...
@Service("messageProvider")
public class ConfigurableMessageProvider implements MessageProvider {
private String message;
@Autowired
public ConfigurableMessageProvider(@Value("This is a configurable message") String
message) {
this.message = message;
}
...
}
From the previous listing, you can see that we use another annotation, @Value, to define the value to
be injected into the constructor. This is the way in Spring you inject values into a bean. Besides simple
strings, you can also use the powerful SpEL for dynamic value injection (more on this later in this chapter).
However, hard-coding the value in the code is not a good idea, since to change it, you would need to
recompile the program. Even if you choose annotation-style DI, a good practice is to externalize those
values for injection. To externalize the message, let's define the message as a Spring bean in the
annotation configuration file, as in Listing 4-29.
Listing 4-29. Using Constructor Injection (Annotation)
<bean id="message" class="java.lang.String"
c:_0="This is a configurable message"/>
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home