Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Thursday, February 29, 2024

What is the ContextLoaderListener in Spring MVC? What does it do?

The ContextLoaderListener is one of the important component of Spring MVC framework. It is like any listener defined by Servlet specification and specified in web.xml using <listener> tag. It is loaded when Spring MVC based web application is deployed in any Servlet container e.g. Tomcat. The ContextLoaderLister of Spring MVC is responsible for loading root ApplicationContext for Spring. The application context is the place where Spring bean lives. If you need reference to a Spring bean either its auto-wired or injected by framework or you can get it directly from application context. In Spring MVC based web application, there can be multiple application context e.g. root application context and context local to each DispatcherServlet.

In simplest of setup, you have two application context, a root application context created by ContextLoaderListener and a web application context created by DispatcherServlet. 

The web application context loaded by DispatcherServlet contains spring beans related to web components e.g. controllers, view resolvers, and handler mappings, whereas root application context contains bean loaded by ContextLoaderListener. 

These beans are typically the service layer and data layer beans which implement the back-end of your Spring MVC application.




How to declare ContextLoaderListener in web.xml?

Prior to Servlet 3.0 specification, you need to declare ContextLoaderListener as a Servlet listener using <listener> tag in the deployment descriptor or web.xml file of your spring MVC based Java web application. 

If you remember, as per Servlet specification, listeners are components which listen for event e.g. ServletContextListener listen for events when ServletContext is created and destroyed and gives you callback in contextInitialized() and contextDestroyed() method. 

Similarly, HttpSessionListener listen for events related to HttpSession e.g. you receive callback on sessionCreated(HttpSessionEvent se) when an HttpSession is created and sessionDestroyed(HttpSessionEvent se) when an HttpSession is destroyed.

The ContextLoaderListener or more precisely org.springframework.web.context.ContextLoaderListener is a bootstrap listener to start up and shut down Spring's root WebApplicationContext. It doesn't perform the startup or shutdown job by itself but simply delegates to ContextLoader as well as to ContextCleanupListener. You can declare the ContextLoaderListener in web.xml as shown below:

<web-app>
	<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
/WEB-INF/config/applicationContext-service.xml
/WEB-INF/config/applicationContext-dao.xml
</param-value>
	</context-param>
</web-app>



Though, it is the not the only way to configure ContextLoaderListener in Spring MVC framework. From Servlet 3.0 specification and Spring 3.1 version you can hook ContextLoaderListener without declaring it on web.xml and by using ServletContainerInitializer interface. 

If a class implements this interface then any Servlet 3.0 specification compliant container e.g. Tomcat 7 or Tomcat 8 will automatically scan and load that class.

Spring provides an implementation of ServletContainerInitializer interface as SpringServletContainerInitializer, which, in turn search for any classes that implement WebApplicationInitializer interface and delegates them for configuration.

Since Spring 3.2, you have a conviinient implemntat of WebApplicationInitializer interface as AbstractAnnotationConfigDispatcherServletInitializer, I know the name is extremely long but that's the case with any Spring class, we have to live with that. If your class extend from this abstract class then it will be automatically discovered when deployed in a Servlet 3.0 container.

You can later use all the @Configuration classes returned by getRootConfigClasses() method of AbstractAnnotationConfigDispatcherServletInitializer to configure the root application context used to be reated by ContextLoaderListener.

class hierarchy of ContextLoaderListener



What is the role of ContextLoaderListener in Spring MVC?

Now that you know what is the ContextLoaderListener and what it does, let's revise its role in a Spring MVC based Java web application. In short it's a listener class which Listens for events e.g. server startup and shutdown. Here are its some of the usage in Spring MVC based Java application.

1. Listens during server startup/shutdown

2. Takes the Spring configuration files as input and creates the beans as per configuration and make it ready (destroys the bean during shutdown)

3. Configuration files can be provided like this in web.xml

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring/root-config.xml</param-value>
</context-param>

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


5. Spring beans loaded by ContextLoaderListener is available to all the DispatcherServlet and that's why service layer and DAO layer beans are loaded by ContextLoaderListener in Spring MVC.


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


7. When ContextLoaderListener is used along with DispatcherServlet, a root web-application-context is created first and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. If a Spring bean is not found in child context then it is searched in parent or root web application context. See the diagram below from the Spring documentation.

What is the ContextLoaderListener in Spring MVC? What does it do?




That's all about What is ContextLoaderListener in Spring MVC, How to configure it and What is the role and use of ContextLoaderListener in Spring MVC based Java web application. As I said, the ContextLoaderListener is used to load the root application context which generally contains the beans shared between multiple DispatcherServlet. It contains beans for service layers and DAO layer, which is not specific to any DispatcherServlet.


Similarly to any other ServletListener, you can declare ContextLoaderListener in web.xml file using <listener> tag. You can also specify the context file location using param-name and param-value tags. From Servlet 3.0 onwards, you can even load root context without declaring ContextLoaderListener into web.xml file. 

You can use the RootConfig class to declare beans loaded by root context. The @Configuration classes returned by getRootConfigClasses() method of AbstractAnnotationConfigDispatcherServletInitializer class can be used to configure the application context reated by ContextLoaderListener. 

Though you should remember that you need a Servlet 3.0 compliant container e.g. Tomcat 7 or higher to make use of this feature.

Another important thing to remember is that ContextLoaderListener is optional. You can still create Spring MVC based web application without declaring ContextLoaderListener in deployment descriptor or web.xml.

Other Spring Framework articles you may like to explore 

    Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or suggestion then please drop a comment and I'll try to answer your question.

    1 comment :

    Anonymous said...

    Is this concept really worth to learn? I didn't even know it exists ..

    Post a Comment