Spring contexts


Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it’s able to communicate with the container.

public interface WebApplicationContext extends ApplicationContext {
 ServletContext getServletContext();

Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface

package org.springframework.web.context;
public interface ServletContextAware extends Aware { 
 void setServletContext(ServletContext servletContext);

There are many things possible to do with the ServletContext instance, for example accessing WEB-INF resources(xml configs and etc.) by calling the getResourceAsStream() method. Typically all application contexts defined in web.xml in a servlet Spring application are Web Application contexts, this goes both to the root webapp context and the servlet’s app context.

Also, depending on web application context capabilities may make your application a little harder to test, and you may need to use MockServletContext class for testing.

Difference between servlet and root context Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it’s not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet contexts:enter image description here

This allows you to run some services as the singletons for the entire application (Spring Security beans and basic database access services typically reside here) and another as separated services in the corresponding servlets to avoid name clashes between beans. For example one servlet context will be serving the web pages and another will be implementing a stateless web service.

This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml


(the root application context is created by ContextLoaderListener which is declared in web.xml


) and servlet tag for the servlet application contexts


Please note that if init-param will be omitted, then spring will use myservlet-servlet.xml in this example.

See also: Difference between applicationContext.xml and spring-servlet.xml in Spring