M Sach M Sach - 1 year ago 74
Java Question

Role/Purpose of ContextLoaderListener in spring?

I am learning spring which is being used in my project.I found the ContextLoaderListener entry in my web.xml . But could not figure out how exactly it helps the developer? In official doc of ContextLoaderListener it says it is to start WebApplicationContext . Regarding WebApplicationContext , api says Interface to provide configuration for a web application . But i am not able to understand what i am achieving with ContextLoaderListener which internally init the WebApplicationContext ?

As per my understanding, ContextLoaderListener reads the spring configuration file (with value given against contextConfigLocation in web.xml), parse 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 Source

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.