Friday, February 8, 2013

Root WebApplicationContext and Child WebApplicationContext

SpringMVC uses one special ApplicationContext: WebApplicationContext in web application.   WebApplicationContext is the extension of ApplicationContext.   It has ServletContext and and beans in WebApplicationContext can access ServletContext if they implement the interface ServletContextAware.

In Spring ApplicationContext can be hierarchical.  One ApplicationContext can have multiple child ApplicationContext and can only have one parent.   Beans in child ApplicationContext can access the beans in parent.

In SpringMVC each DispatcherServlet has one WebApplicationContext.   So there may be more than WebApplicationContext if the web application has multiple DispatcherServlet. By default Spring always look for the ApplicationContext: your_dispatcherservlet_name-servlet.xml. These DispatcherServlet related WebApplicationContext should have MVC-specific configurations.   Other non MVC-specific configuration such as the beans for service or persistence layer should be in root WebApplicationContext.

In SpringMVC the root WebApplicationContext is bootstrapped by using ContextLoadListener specified as Listener in web.xml.




The above is the example of configuration in web.xml for root WebApplicationContext.

MVC specific WebApplicationContext is loaded for each of DispatcherServlet.  It is defined in each of servlet in web.xml. The below is an example of configuration for a DispatcherServelt where a child WebApplicationContext is specified.




  1. Hi, nice article. Is there a thumb rule for what should go to the root WebApplicationContext context and what should go to the dispatcher WebApplicationContext context? For example, messageSource bean, Services bean, Components bean, etc?

  2. Servlet WebApplicationContext context - You should have all the MVC (web) related beans such as Controllers, ViewResolvers etc..,
    ROOT WebApplicationContext context - You should have all other beans such as Service, DataSource etc..,