public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-xml.xml");
ctx.refresh();
MessageRenderer messageRenderer = ctx.getBean("messageRenderer",
MessageRenderer.class);
messageRenderer.render();
}
}
Like the previous section, you can swap the app-context-xml.xml file with app-context-
annotation.xml in the provided source code for this chapter, and you will find that both cases produce
the same result; i.e., "Hello World!" is printed.
Using Constructor Injection
In the previous example, the MessageProvider implementation, HelloWorldMessageProvider, returned
the same hard-coded message for each call of the getMessage() method. In the Spring configuration file,
you can easily create a configurable MessageProvider that allows the message to be defined externally, as
shown in Listing 4-26.
Listing 4-26. The ConfigurableMessageProvider Class (XML)
package com.apress.prospring3.ch4.xml;
import com.apress.prospring3.ch4.MessageProvider;
public class ConfigurableMessageProvider implements MessageProvider {
private String message;
public ConfigurableMessageProvider(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
As you can see, it is impossible to create an instance of ConfigurableMessageProvider without
providing a value for the message (unless you supply null). This is exactly what we want, and this class is
ideally suited for use with Constructor Injection. Listing 4-27 shows how you can redefine the
messageProvider bean definition to create an instance of ConfigurableMessageProvider, injecting the
message using Constructor Injection.
Listing 4-27. Using Constructor Injection (XML)
<bean id="messageProvider" class="com.apress.prospring3.ch4.xml.ConfigurableMessageProvider">
<constructor-arg>
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home