What is ContextLoaderListener in Spring MVC? Example Tutorial

The ContextLoaderListner is one of the essential components of the Spring MVC framework, probably the most important after the DispatcherServlet itself. It is used to create the root context and responsible for loading beans, which are shared by multiple DispatcherServlet like beans related to the service layer and data access layer. In general, When you develop Spring MVC based web applications and also using Spring in the services layer, you need to provide two application-contexts. The first one is configured using ContextLoaderListener, and the other is set using DispatcherServlet. The DispatcherServlet is responsible for loading web component-specific beans like controllers, view resolvers, and handler mappings while, as I said before, ContextLoaderListener is accountable for loading middle-tier and data-tier beans which forms the back end of Spring applications.

The ContextLoaderListener is like any other Servlet listener, and it has to be declared in the deployment descriptor to listen to events. It listens for startup and shutdown of the server by implementing ServletContextListener and accordingly creates and destroys Spring-managed beans.

Though, web.xml is just one way to configure ContextLoaderListener in the Spring MVC application. From Spring 3.1 and Servlet 3.0, you can also configure ContextLoaderListener without deployment descriptor and only using Java Configurations.

Spring 3.2 provides an abstract class called AbstractAnnotationConfigDispatcherServletInitializer, which has methods to return @Configuration courses for both the root context and the web context specific to the DispatcherServlet.

The getRootConfigClasses() method of this class returns all @Configuration class, which should be part of the root context, and @getServletConfigClasses() method returns all @Configuration courses, which should be specific to the DispatcherServlet. Though, if you are not familiar with Java Configuration, Spring Framework 5: Beginner to Guru course on Udemy is an excellent resource to start with.

Though, one thing you must remember that this facility is only available from Servlet 3.0, and you need a Servlet 3.0 compliant web server like Tomcat 7 or higher to programmatically create root context. If you are running in Tomcat 6 or lower version, then you have to use the web.xml to declare ContextLoaderListener.

One more thing to keep in mind is that ContextLoaderListener is optional. You can still create a Spring MVC web application without using this listener because all web-specific beans are loaded by DispatcherServlet itself.





10 points about ContextLoaderListener in Spring MVC

Here are some of the essential things about org.springframework.web.context.ContextLoaderListener class, a Java and Spring developer, should know. It contains some of the basic details as well as some lesser-known features of ContextLoaderListener, which is useful for both Spring 5.0 Developer Certification and Java Spring Boot Interviews, which requires candidates from a Spring background.


1. ServletContextListener

The ContextLoaderListener is like any Servlet listener and implements both EventListener and ServletContextListener. Hence it listens for server startup and shutdown events.

2. Manages Spring Beans

Its job is to take the Spring configuration files as input and creates the Spring-managed beans as per configuration and make them ready during server startup and destroys them during server shutdown. Though it didn't do that itself, instead, just delegate to ContextLoader as well as to ContextCleanupListener.

If you are not familiar with the Spring IOC container, It's better to join a comprehensive Spring Framework course like Spring Master Class - Beginner to Expert by Ranga Karnan, a fellow blogger and experienced Java developer with Spring.

ContextLoaderListener in Spring MVC - 10 things you should know


3. Declaring ContextLoaderListener on web.xml

You can declare ContextLoaderListener in deployment descriptor or web.xml as follows:

<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>
<servlet>
        <servlet-name>dispatcher</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>
            /WEB-INF/config/servlet-context.xml
           ***/WEB-INF/config/applicationContext.xml***
         </param-value>
</init-param>
    <load-on-startup>1</load-on-startup>
 </servlet>
 
</web-app>


4. Initialization of Root Application Context

The actual initialization work for the root application context is performed by ContextLoader class, which is called by ContextLoaderListener. This class looks for a "contextClass" parameter at the web.xml context-param level to find the type of the context class. If no contextClass is defined, then by default, it uses XmlWebApplicationContext.

It also processes a "contextConfigLocation" context-param and passes its value to the context instance. This parameter specifies the path for the spring configuration file. It may contain multiple file paths that can be separated by any number of commas and spaces, like "WEB-INF/applicationContext1.xml, WEB-INF/applicationContext2.xml".

Even, Ant-style path patterns are supported as well, like "WEB-INF/*Context.xml,WEB-INF/spring*.xml" or "WEB-INF/**/*Context.xml". If not explicitly specified, the context implementation is supposed to use a default location (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml").


5. Shared Parent Context

Along with loading the root application context, this class can optionally load or obtain and hook up a shared parent context to the root application context. You can see the loadParentContext(ServletContext) method for more information. You can also read Spring in Action 5th Edition for more details, one of my favorite books to learn Spring, and every Java developing using Spring should read it.

best book to learn Spring MVC


6. Root Web ApplicaitonContext

When ContextLoaderListener is used along with DispatcherServlet, a root web-application-context is created first, as said earlier, and a child-context is also created by dispatcher servlet which is attached to the root application-context. Refer documentation here.


7. Root Context

In Servlet 3.0 compliant container, you can create root context without defining ContextLoaderListener in the deployment descriptor file. From Servlet 3.0 specification, announced in 2009, there is a ServletContainerInitializer interface, any class which implements this interface is automatically discovered by Servlet 3.0 compliant servlet container like Tomcat 7 and higher.


8. ServletContainerInitializer

Spring provides an implementation of ServletContainerInitializer interface as SpringServletContainerInitializer and from Spring 3.2 you can also extend from AbstractAnnotationConfigDispatcherServletInitializer class. This can create both root context and web-context specific to the DispatcherServlet.

The getServletCofnigClasses() method of this class return all @Configuration classes which can be loaded into web context and getRootConfigClasses() method returns all @Configuration classes which can be part of root context.

9. Used for loading Service and Data Beans

In Spring MVC, the DispatcherServlet is expected to load the bean configuration, web components such as controllers, view resolvers, and handler mappings while ContextLoaderListener is expected to load beans from service-tier and data-tier which forms the back end of the application.

10. Access to ServletContext

Another benefit of the ContextLoaderListener is that it creates a WebApplicationContext and WebApplicationContext provides access to the ServletContext via ServletContextAware beans and the getServletContext() method. It also ties the lifecycle of the ApplicationContext to the lifecycle of the ServletContext as explained in the classic Introduction to Spring MVC 4 By Bryan Hanseon Pluralsight.

best course to learn Spring MVC



That's all about ContextLoaderListener in Spring MVC. As I said, it is one of the essential components of the Spring MVC framework and used to create root context in Spring web applications, which is shared by different contexts loaded by each DispatcherServlet. It usually contains generic spring beans like which are not web specifics like beans from service classes and Data Access object.

You can configure ContextLoaderListener in the deployment descriptor, and you can even provide it the config location for the spring configuration file. The ContextLoader listener listens for server startup and shutdown and accordingly creates and destroyed Spring beans.

From Servlet 3.0 onwards, you can even configure ContextLoaderListener and root context without using a deployment descriptor or web.xml file. The Servlet 3.0 specification provides an interface called ServletContainerInitializer, and any class which implements this interface will automatically be scanned and loaded by any Servlet 3.0 compliant container like Tomcat 7 or Tomcat 8.

From the Spring 3.2 version, Spring provides a convenient class called AbstractAnnotationConfigDispatcherServlet, whose getRootConfig() method can be used to instantiate bean, which lives in the root context.

The last thing you should remember about ContextLoaderListener is that it's optional in Spring MVC. You can still create a Spring MVC-based web application without declaring ConextLoaderListener and just declaring DispatcherServlet because all web-specific components like controllers, view resolvers, and handler mappings are defined in the WebApplicationContext created by the Dispatcher servlet.



Other Spring Articles and Resources you may like:
  • Top 5 Spring and Hibernate Training courses (courses)
  • Difference between @Compoent, @Service, and @Controller in Spring? (answer)
  • 5 Free Spring Framework and Spring Boot Courses (courses)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • 15 Spring Boot Interview Questions with Answers (questions)
  • Top 5 Courses to learn Microservices in Spring? (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • 5 Spring Framework Books For Java Developers (books)
  • 20 REST with Spring Interview Questions for Web developers (questions)
  • 5 Spring Boot Features Java developer should learn (features)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • 3 ways to learn Core Spring or Spring MVC better (article)
  • 6 Resources to learn Spring Framework in Depth (resources)
  • Top 10 Spring Framework Interview Questions (questions)
  • 10 Spring MVC Annotations Every Java Dev should know (annotations)

Thanks for reading this article so far. If you find these Spring MVC tutorials about ContextLoaderLister useful, then please share them with your friends and colleagues on Facebook and Twitter. If you have any questions or feedback, then please drop a note.

P. S. - If you are new to Spring Framework and looking for a hands-on course, then Learn Spring: The Certification Class by Eugen Paraschiv of Baeldung is probably the best course to learn Spring 5 and Spring Boot 2 from scratch, in a guided, code-focused way.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.