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.
<web-app>
............
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/META-INF/applicationContext.xml
/WEB-INF/classes/META-INF/applicationSecurity.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
............
</web-app>
|
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.
<web-app>
...........
.
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
............
</web-app>
|
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?
ReplyDeleteServlet WebApplicationContext context - You should have all the MVC (web) related beans such as Controllers, ViewResolvers etc..,
ReplyDeleteROOT WebApplicationContext context - You should have all other beans such as Service, DataSource etc..,