Listing 2-10. Using Spring's ApplicationContext
package com.apress.prospring3.ch2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldSpringDI {
public static void main(String[] args) {
// Initialize Spring ApplicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext
("META-INF/spring/app-context.xml");
MessageRenderer mr = ctx.getBean("renderer", MessageRenderer.class);
mr.render();
}
}
In Listing 2-10, you can see that the main() method obtains an instance of
ClassPathXmlApplicationContext (the application configuration information is loaded from the file
META-INF/spring/app-context.xml in the project's classpath), typed as ApplicationContext, and from
this, it obtains the MessageRenderer instances using the ApplicationContext.getBean() method. Don't
worry too much about the getBean() method for now; just know that this method reads the application
configuration (in this case an XML file), initializes Spring's ApplicationContext environment, and then
returns the configured bean instance. This XML file (app-context.xml) serves the same purpose as the
one we used for MessageSupportFactory (see Listing 2-11).
Listing 2-11. Spring XML Application Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="provider" class="com.apress.prospring3.ch2.HelloWorldMessageProvider"/>
<bean id="renderer" class="com.apress.prospring3.ch2.StandardOutMessageRenderer"
p:messageProvider-ref="provider"/>
</beans>
The previous file shows a typical Spring ApplicationContext configuration file. First, Spring's
namespaces are declared, and the default namespace is beans, which is used to declare the beans that
need to be managed by Spring, and its dependency requirements (for the above example, the renderer
bean's messageProvider property is referencing the provider bean) for Spring to resolve and inject those
dependencies.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home