Role/Purpose of ContextLoaderListener in Spring?

M Sach picture M Sach · Aug 5, 2012 · Viewed 140k times · Source

I am learning Spring Framework which is being used in my project. I found the ContextLoaderListener entry in my web.xml file. But could not figure out how exactly it helps a developer?

In the official documentation of ContextLoaderListener it says it is to start WebApplicationContext. Regarding WebApplicationContext JavaDocs say:

Interface to provide configuration for a web application.


But I am not able to understand what I am achieving with ContextLoaderListener which internally initializes the WebApplicationContext ?

As per my understanding, ContextLoaderListener reads the Spring configuration file (with value given against contextConfigLocation in web.xml), parses it and loads the singleton bean defined in that config file. Similarly when we want to load prototype bean, we will use same webapplication context to load it. So we initialize the webapplication with ContextLoaderListener so that we read/parse/validate the config file in advance and whenever we wan to inject dependency we can straightaway do it without any delay. Is this understanding correct?

Answer

sourcedelica picture sourcedelica · Aug 5, 2012

Your understanding is correct. The ApplicationContext is where your Spring beans live. The purpose of the ContextLoaderListener is two-fold:

  1. to tie the lifecycle of the ApplicationContext to the lifecycle of the ServletContext and

  2. to automate the creation of the ApplicationContext, so you don't have to write explicit code to do create it - it's a convenience function.

Another convenient thing about the ContextLoaderListener is that it creates a WebApplicationContext and WebApplicationContext provides access to the ServletContext via ServletContextAware beans and the getServletContext method.