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?
Your understanding is correct. The
ApplicationContextis where your Spring beans live. The purpose of theContextLoaderListeneris two-fold:to tie the lifecycle of the
ApplicationContextto the lifecycle of theServletContextandto automate the creation of the
ApplicationContext, so you don’t have to write explicit code to create it – it’s a convenience function.Another convenient thing about the
ContextLoaderListeneris that it creates aWebApplicationContextand provides access to theServletContextviaServletContextAwarebeans and thegetServletContextmethod.