Skip to content

Add a spring context to your web application

Web application contexts

You can use the following steps to add a Spring context that will be created and destroyed with your web application.

Add the following

web.xml
<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.

Add the following dependency

pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>2.5.6</version>
</dependency>

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 at 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");