DispatcherServlet
expects a WebApplicationContext
(an extension of the regular ApplicationContext
) for its own configuration. The WebApplicationContext
has a reference to the ServletContext
and the Servlet
it is associated with. It is also bound to the ServletContext
so applications can use the static RequestContextUtils
methods to find the WebApplicationContext
if they need access to it.
For many applications, it is enough to have one WebApplicationContext
. It is also possible to have a hierarchy of contexts, where one root WebApplicationContext
is shared by multiple DispatcherServlet
(or other Servlet
) instances, each with its own child configuration WebApplicationContext
.
The Root WebApplicationContext
typically contains infrastructure beans, such as data stores and business services, that should be shared across multiple Servlet
instances. These beans are effectively inherited and can be overridden (that is, re-declared) in a servlet-specific WebApplicationContext
child, which typically contains beans local to that Servlet
. The following image shows this relationship:

The following example configures the WebApplicationContext
hierarchy:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
class MyWebAppInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>> {
return arrayOf(RootConfig::class.java)
}
override fun getServletConfigClasses(): Array<Class<*>> {
return arrayOf(App1Config::class.java)
}
override fun getServletMappings(): Array<String> {
return arrayOf("/app1/*")
}
}
getRootConfigClasses()
and
null
from
getServletConfigClasses()
.
The following example shows the equivalent of web.xml
:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app1-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app1</servlet-name>
<url-pattern>/app1/*</url-pattern>
</servlet-mapping>
</web-app>
contextConfigLocation
empty.
GO TO FULL VERSION