ContextLoaderListener in Spring MVC - 10 Things Java Programmer Should Know

The ContextLoaderListner is one of the important components of the Spring MVC framework, probably the most important after DispatcherServlet itself. It is used to create 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 application 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 configured 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 responsible 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 destroy Spring-managed beans.

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

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

The getRootConfigClasses() method of this class return all @Configuration class which should be part of root context and @getServletConfigClasses() method returns all @Configuration classes 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 a good 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 complaint 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 Spring MVC based 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 important things about org.springframework.web.context.ContextLoaderListener class a Java and Spring developer should know. It contains some of the fundamental details as well as some lesser known features of ContextLoaderListener, which is useful for both Spring 5.0 Developer Certification and Java Interviews which requires candidates from Spring background.

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

2) Its job is to take the Spring configuration files as input and creates the spring managed beans as per configuration and make it 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 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) 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) 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 and if no contextClass is defined than 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 which 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) 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) 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) 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) 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) In Spring MVC, the DispatcherServlet is expected to load the bean configuration, web components such as controllers, view resolve 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) 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 Hansen by Bryan Hansen course on Pluralsight.

best course to learn Spring MVC



That's all about ContextLoaderListener in Spring MVC. As I said, it is one of the important 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 create and destroyed Spring beans.

From Servlet 3.0 onwards, you can even configure ContextLoaderListener and root context without using 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 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 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 Dispatcher servlet.

Further Learning
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert
Introduction to Spring MVC 4 By Bryan Hansen


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)
  • 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)
  • 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 annotations useful then please share 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 Paraschive of Bealdug 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