Search This Blog

Saturday, 24 November 2012

Springs' ContextLoaderListener

In an earlier example we show how to load beans from multiple configuration files. This is mostly needed in web applications where we write the different bean definitions in different layers.
As we saw in our basic MVC example, Spring 's MVC dispatcher servlet is responsible for loading the beans in our XML configuration file.This is from Spring Documentation:
A web application can define any number of DispatcherServlets. 
Each servlet will operate in its own namespace, loading its own 
application context with mappings, handlers, etc
This implies that any beans that are loaded from the dispatcher servlet are only accessible in the scope of the Dispatcher servlet code. If there is any other servlet, it wont be able to access any of the beans. The only way to access the beans is :
Only the root application context as loaded by ContextLoaderListener, if any, will be shared.
This means that beans loaded using the servlet listener will be available to all servlets.
<!-- The context params that read by ContextLoaderListener  -->
<!-- This listener will load other application context files in addition 
            to springweb-servlet.xml -->
The Listener is an implementation of ServletContextListener. On context initialization it loads the beans defined in the context param and adds them to the root application context (in this case the WebApplicationContext) Any DispatcherServlets or other Spring managed Servlets like the MessageDispatcherServlet define their own WebAplicationContexts which inherit from the root context. Thus the beans made available via the WebApplicationContext are now accessible to all.

No comments:

Post a Comment