public class StandardOutMessageRenderer implements MessageRenderer {
package com.apress.prospring3.ch4.annotation;
import org.springframework.stereotype.Service;
// Rest of codes omitted
@Service("messageProvider")
public class HelloWorldMessageProvider implements MessageProvider {
From the previous code sample, you use Spring's @Service annotation to specify that the bean
provides services that other beans may require, passing in the bean name as the parameter. When
bootstrapping Spring's ApplicationContext with the XML configuration in Listing 4-15, Spring will seek
out those components and instantiate the beans with the specified names.
Using either approach doesn't affect the way you obtain the beans from ApplicationContext. Listing
4-20 shows the example code to obtain the message provider.
Listing 4-20. Declare Spring Beans (Testing)
package com.apress.prospring3.ch4;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DeclareSpringComponents {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-xml.xml");
ctx.refresh();
MessageProvider messageProvider = ctx.getBean("messageProvider",
MessageProvider.class);
System.out.println(messageProvider.getMessage());
}
}
From Listing 4-20, instead of the DefaultListableBeanFactory, an instance of
GenericXmlApplicationContext was instantiated. The GenericXmlApplicationContext class implements
the ApplicationContext interface and is able to bootstrap Spring's ApplicationContext from the
configurations defined in XML files.
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.
Listing 4-21 (app-context-xml.xml) and Listing 4-22 (app-context-annotation.xml) recap the
configuration files content for both XML and annotation-style configuration that we have discussed so
far.
Listing 4-21. XML Configuration (app-context-xml.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home