Quick Table of Contents
How to add a spring context to your web application.
You can use the following steps to add a Spring context that will be created and destroyed with your web application.
1. Edit web.xml
Add the following:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:com/magicmonster/sample/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In the above example I've assumed that the spring bean xml definition is in applicationContext.xml.
2. Edit pom.xml for maven
Add the following dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>2.5.6</version>
</dependency>3. Explanation
The ContextLoaderListener will create the spring context specified by contextConfigLocation. The spring context's lifecycle will match the web application. It will be started and stopped when the webapp is started and stopped.
To get a the beans in the spring context, get access to the ServletContext.
javax.servlet.ServletContext servletContext = ..
org.springframework.web.context.WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
SampleService service = (SampleService) webApplicationContext.getBean("sampleService");

