Looking at the Spring Application Context
by, 11-15-2011 at 02:13 PM (2119 Views)
In order to take advantage of the full power of the Spring framework, you need to use Spring’s most advanced container, the application context. The ApplicationContext is similar to a BeanFactory. Both load bean definitions, wire beans together, and dispense beans upon request. But an ApplicationContext also does the following:
- Application contexts provide a generic way to load other resources, such as images.
- Application contexts can publish events to beans that are registered as listeners.
- Application contexts provide a means for resolving text messages, including support for internationalization (I18N) of those messages.
An ApplicationContext is the preferred choice over a BeanFactory in nearly all applications. This is because of the richer functionality offered compared to a BeanFactory. The only times it is recommended to use a BeanFactory is wen resources are scarce.
There are three commonly used implementations of ApplicationContext:
- ClassPathXmlApplicationContext—Loads a context definition from an XML file located in the class path, treating context definition files as class path resources.
- FileSystemXmlApplicationContext—Loads a context definition from an XML file in the filesystem.
- XmlWebApplicationContext—Loads context definitions from an XML file contained within a web application.
Here is an example of how to use the FileSystemXmlApplicationContext:
You can also load the application context using the application’s class path with ClassPathXmlApplicationContext:Java Code:ApplicationContext context = new FileSystemXmlApplicationContext("c:/springexamples.xml");
The FileSystemXmlApplicationContext will look for springexamples.xml in a specific location. In the case of ClassPathXmlApplicationContext of will look for cars.xml in the class path.Java Code:ApplicationContext context = new ClassPathXmlApplicationContext("springexamples.xml");
Similarly to a BeanFactory, an ApplicationContext uses the getBean() method. A key difference is an application context preloads all singleton beans upon context startup to ensure that they are ready for use when required whereas a bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. That’s the basics of configuring a Spring container.