How to add a spring context to your web application

Published: Tuesday, 12 July 2011
java spring spring-web

Web application contexts

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

Edit web.xm;

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.

Edit pom.xml for maven

Add the following dependency

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

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