Learn Java for Web Development

(Tina Meador) #1
CHAPTER 5: Building Java Web Applications with Spring Web MVC 211

Application Context

Spring comes with several implementations of the ApplicationContext interface out of the box.
The three most commonly used are the following:


   ClassPathXmlApplicationContext: Loads a context definition from an XML file
located in the class path
 FileSystemXmlApplicationContext: Loads a context definition from an XML file
in the file system
 XmlWebApplicationContext: Loads context definitions from an XML file
contained within a web application

In stand-alone applications, it is common to create an instance of ClassPathXmlApplicationContext
or FileSystemXmlApplicationContext.


Following Figure 5-1, you have to instantiate the Spring IoC container (ApplicationContext) for it to
create bean instances by reading their configurations (configuration metadata). Then, you can get
the bean instances from the IoC container to use.


Listing 5-8 illustrates the instantiation of the ClassPathXmlApplicationContext, an implementation
of ApplicationContext. The ClassPathXmlApplicationContext implementation builds an application
context by loading an XML configuration file from the class path.


Listing 5-8. Instantiation of ClassPathXmlApplicationContext


ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");


Listing 5-9 illustrates the instantiation of the FileSystemXmlApplicationContext.


Listing 5-9. Instantiation of the FileSystemXmlApplicationContext


ApplicationContextcontext=new FileSystemXmlApplicationContext("c:/beans.xml");


Note The FileSystemXmlApplicationContext looks for beans.xml in a specific location within the
file system, whereas ClassPathXmlApplicationContext looks for beans.xml anywhere in the class
path (including JAR files).

In the section that follows, you will learn how to use the application context when you create your
first Spring-based stand-alone application.

Free download pdf