Purpose of ContextLoaderListener – Spring MVC

When we are working with Spring MVC and are also using Spring in the services layer, we provide two application-contexts. The first one is configured using ContextLoaderListener and the other with DispatcherServlet. A sample configuration in web.xml is mentioned below:


    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>

After reading the Spring documentation, following is the understanding:

a) Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here.

b) ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).

c) DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.

d) When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. Refer documentation here.

Refer to the diagram below from the Spring documentation.