Why does Spring MVC need at least two contexts?

Having a root web application context plus a child servlet context is just an option. If you know that your application won’t have a second servlet, it’s arguably simpler to have one single Spring context for the whole web application.

You can achieve that setup by simply removing the ContextLoaderListener (and the accompanying contextConfigLocation context-param) from your web.xml and moving all bean definitions into the xml defining the servlet context ([servlet-name]-servlet.xml).

This is possible, because the FrameworkServlet (super-class of DispatcherServlet) doesn’t care if there is a root application context when creating the servlet context. It just relays the root context as the parent if available. See related code here.

Leave a Comment