ContextLoaderListener role and purpose


Basically you can isolate your root application context and web application context using ContextLoaderListner.
Listener class - Listens on an event (Eg.. Server startup/shutdown)
ContextLoaderListener -
  1. Listens during server start up/shutdown
  2. Takes the Spring configuration files as input and creates the beans as per configuration and make it ready (destroys the bean during shutdown)
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.

ContextLoaderListner is a Servlet listener that loads all the different configuration files (service layer configuration, persistence layer configuration etc) into single spring application context.
This helps to split spring configurations across multiple XML files.
Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definition and stores it in the ServletContext of your web application.
ContextLoaderListener supports injecting the root web application context via the ContextLoaderListener(WebApplicationContext) constructor, allowing for programmatic configuration in Servlet 3.0+ environments. 


If we write web.xml without ContextLoaderListener then we cant give the athuntication using customAuthenticationProvider in spring security. Because DispatcherServelet is the child context of ContextLoaderListener, customAuthenticationProvider is the part of parentContext that is ContextLoaderListener. So parent Context cannot have the dependencies of child context. And so it is best practice to write spring-context.xml in contextparam instead of write it in the initparam.

Comments