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 {
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { App1Config.class };
    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/*")
If there is no need for an application context hierarchy, applications can return the entire configuration via getRootConfigClasses() and null from getServletConfigClasses().

The following example shows the equivalent of web.xml:

If there is no need for an application context hierarchy, applications can configure only the "root" context and leave the servlet parameter contextConfigLocation empty.