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  -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/file1.xml
        classpath:file2.xml
    </param-value>
</context-param>
    
<!-- This listener will load other application context files in addition 
            to springweb-servlet.xml -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
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