[Spring] talking about ContextLoaderListener and springcontextloader

Source: Internet
Author: User

[Spring] talking about ContextLoaderListener and springcontextloader

Generally, in projects developed using SpingMVC, ContextLoaderListener listeners are configured in the web. xml file as follows:

<listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

The listener is configured to automatically assemble the configuration information in ApplicationContext when the web container is started. Check the source code of ContextLoaderListener:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {    public ContextLoaderListener() {    }    public ContextLoaderListener(WebApplicationContext context) {        super(context);    }    @Override    public void contextInitialized(ServletContextEvent event) {        initWebApplicationContext(event.getServletContext());    }    @Override    public void contextDestroyed(ServletContextEvent event) {        closeWebApplicationContext(event.getServletContext());        ContextCleanupListener.cleanupAttributes(event.getServletContext());    }}

From the above we can see that ContextLoaderListener inherits the ContextLoader class and implements the ServletContextListener interface. The ServletContextListener Interface contains only the initialization and destruction methods, as shown below:

public interface ServletContextListener extends EventListener {    /**     ** Notification that the web application initialization     ** process is starting.     ** All ServletContextListeners are notified of context     ** initialization before any filter or servlet in the web     ** application is initialized.     */    public void contextInitialized ( ServletContextEvent sce );    /**     ** Notification that the servlet context is about to be shut down.     ** All servlets and filters have been destroy()ed before any     ** ServletContextListeners are notified of context     ** destruction.     */    public void contextDestroyed ( ServletContextEvent sce );}

The main function of ContextLoaderListener is implemented in the inherited ContextLoader class. Next, let's take a look at the context Initialization Method in ContextLoaderListener, that is:

/** * Initialize the root web application context. */@Overridepublic void contextInitialized(ServletContextEvent event) {    initWebApplicationContext(event.getServletContext());}

Follow up the initWebApplicationContext () method, and the implementation of its call is in the ContextLoader class:

/*** Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@ link # CONTEXT_CLASS_PARAM contextClass}" and * "{@ link # CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @ param servletContext current servlet context * @ return the new WebApplicationContext * @ see # ContextLoader (WebApplicationContext) * @ see # CONTEXT_CLASS_PARAM * @ see # CONFIG_LOCATION_PARAM */public WebApplicationContext initWebApplicationContext (ServletContext servletContext) {// determine whether the context in ServletContext already exists, if yes, the load or configuration information is incorrect (see the exception information thrown below) if (servletContext. getAttribute (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE )! = Null) {throw new IllegalStateException ("Cannot initialize context because there is already a root application context present-" + "check whether you have multiple ContextLoader * definitions in your web. xml! ");} Log logger = LogFactory. getLog (ContextLoader. class); servletContext. log ("Initializing Spring root WebApplicationContext"); if (logger. isInfoEnabled () {logger.info ("Root WebApplicationContext: initialization started");} long startTime = System. currentTimeMillis (); try {// Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this. con Text = null) {// create the WebApplicationContext context this. context = createWebApplicationContext (servletContext);} if (this. context instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this. context; if (! Cwac. isActive () {// The context has not yet been refreshed-> provide services such as // setting the parent context, setting the application context id, etc if (cwac. getParent () = null) {// The context instance was injected without an explicit parent-> // determine parent for root web application context, if any. // load the parent context ApplicationContext parent = loadParentContext (servletContext); cwac. se TParent (parent);} // initialize WebApplicationContext. The initialization parameters are from the web. configureAndRefreshWebApplicationContext (cwac, servletContext) ;}} servletContext. setAttribute (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this. context); ClassLoader ccl = Thread. currentThread (). getContextClassLoader (); if (ccl = ContextLoader. class. getClassLoader () {currentContext = this. context;} else if (cc L! = Null) {currentContextPerThread. put (ccl, this. context);}/* omitting some code */}

In the initWebApplicationContext () method above, use createWebApplicationContext (servletContext) to create the root context, and then save the root context to ServletContext. Let's look at the source code of createWebApplicationContext (servletContext:

/*** Instantiate the root WebApplicationContext for this loader, either the * default context class or a custom context class if specified. * <p> This implementation expects custom contexts to implement the * {@ link ConfigurableWebApplicationContext} interface. * Can be overridden in subclasses. * <p> In addition, {@ link # customizeContext} gets called prior to refreshing the * context, allowing subc Lasses to perform custom modifications to the context. * @ param SC current servlet context * @ return the root WebApplicationContext * @ see ConfigurableWebApplicationContext */protected WebApplicationContext createWebApplicationContext (ServletContext SC) {// determine the type of the loaded context, the parameter is in the web. contextClass configured in xml (default is used if no contextClass is used) Class <?> ContextClass = determineContextClass (SC); if (! ConfigurableWebApplicationContext. class. isAssignableFrom (contextClass) {throw new ApplicationContextException ("Custom context class [" + contextClass. getName () + "] is not of type [" + ConfigurableWebApplicationContext. class. getName () + "]");} // initialize WebApplicationContext and convert it to the ConfigurableWebApplicationContext type return (ConfigurableWebApplicationContext) BeanUtils. instantiateClass (contextClass );}

From the source code above, we can see that the context created using the createWebApplicationContext method must implement the ableablewebapplicationcontext interface. Otherwise, an exception is thrown. The determineContextClass method in the createWebApplicationContext (servletContext) method above is used to find the Class type of the root context. See the source code:

/** * Return the WebApplicationContext implementation class to use, either the * default XmlWebApplicationContext or a custom context class if specified. * @param servletContext current servlet context * @return the WebApplicationContext implementation class to use * @see #CONTEXT_CLASS_PARAM * @see org.springframework.web.context.support.XmlWebApplicationContext */protected Class<?> determineContextClass(ServletContext servletContext) {    String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);    if (contextClassName != null) {        try {            return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());        }        catch (ClassNotFoundException ex) {            throw new ApplicationContextException(                    "Failed to load custom context class [" + contextClassName + "]", ex);        }    }    else {        contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());        try {            return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());        }        catch (ClassNotFoundException ex) {            throw new ApplicationContextException(                    "Failed to load default context class [" + contextClassName + "]", ex);        }    }}

As shown in the preceding figure, if the contextClass type implementing ableablewebapplicationcontext is configured in web. xml, that parameter is used. Otherwise, the default XmlWebApplicationContext is used.

In the initWebApplicationContext () method of the ContextLoader class above, there is also the method loadParentContext (ServletContext servletContext) for loading the parent context. Let's take a look at its source code:

/** * Template method with default implementation (which may be overridden by a * subclass), to load or obtain an ApplicationContext instance which will be * used as the parent context of the root WebApplicationContext. If the * return value from the method is null, no parent context is set. * <p>The main reason to load a parent context here is to allow multiple root * web application contexts to all be children of a shared EAR context, or * alternately to also share the same parent context that is visible to * EJBs. For pure web applications, there is usually no need to worry about * having a parent context to the root web application context. * <p>The default implementation uses * {@link org.springframework.context.access.ContextSingletonBeanFactoryLocator}, * configured via {@link #LOCATOR_FACTORY_SELECTOR_PARAM} and * {@link #LOCATOR_FACTORY_KEY_PARAM}, to load a parent context * which will be shared by all other users of ContextsingletonBeanFactoryLocator * which also use the same configuration parameters. * @param servletContext current servlet context * @return the parent application context, or {@code null} if none * @see org.springframework.context.access.ContextSingletonBeanFactoryLocator */protected ApplicationContext loadParentContext(ServletContext servletContext) {    ApplicationContext parentContext = null;    String locatorFactorySelector = servletContext.getInitParameter(LOCATOR_FACTORY_SELECTOR_PARAM);    String parentContextKey = servletContext.getInitParameter(LOCATOR_FACTORY_KEY_PARAM);    if (parentContextKey != null) {        // locatorFactorySelector may be null, indicating the default "classpath*:beanRefContext.xml"        BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(locatorFactorySelector);        Log logger = LogFactory.getLog(ContextLoader.class);        if (logger.isDebugEnabled()) {            logger.debug("Getting parent context definition: using parent context key of '" +                    parentContextKey + "' with BeanFactoryLocator");        }        this.parentContextRef = locator.useBeanFactory(parentContextKey);        parentContext = (ApplicationContext) this.parentContextRef.getFactory();    }    return parentContext;}

The source code above is to set the parent context for the context based on locatorFactorySelector and parentContextKey, provided that we are on the web. these two parameters are configured in xml. However, these two parameters are rarely set during development. The parent context is empty if no such parameter is set from the large comments in the source code above.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.