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.

Edit web.xml

Add the following:



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



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

Published: Tuesday, 12 July 2011