SpringMVC容器初始化篇----ContextLoaderListener

ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。
因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
ContextLoaderListener启动的上下文为根上下文,DispatcherServlet所创建的上下文的的父上下文即为此根上下文,可在FrameworkServlet中的initWebApplicationContext中看出。

通常在web.xml中如下配置:


<context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:spring.xml  
        </param-value>  
    </context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener  
        </listener-class>  
    </listener>  

层次结构


ContextLoaderListener继承ContextLoader类实现ServletContextListener接口
其中它的主要功能是在ContextLoader中实现,ServletContextListener接口在package javax.servlet中以为servlet的api,
ServletContextListener又继承EventListener,此乃package java.util;中的接口了。
EventListener接口中无任何方法。
ServletContextListener中含有2方法,一个初始化一个销毁。


/** 
     * Receives notification that the web application initialization 
     * process is starting. 
     * 
     * <p>All ServletContextListeners are notified of context 
     * initialization before any filters or servlets in the web 
     * application are initialized. 
     * 
     * @param sce the ServletContextEvent containing the ServletContext 
     * that is being initialized 
     */  
    public void contextInitialized(ServletContextEvent sce);  
  
    /** 
     * Receives notification that the ServletContext is about to be 
     * shut down. 
     * 
     * <p>All servlets and filters will have been destroyed before any 
     * ServletContextListeners are notified of context 
     * destruction. 
     * 
     * @param sce the ServletContextEvent containing the ServletContext 
     * that is being destroyed 
     */  
    public void contextDestroyed(ServletContextEvent sce);  

ContextLoaderListener初始化容器时序图
![](http://upload-images.jianshu.io/upload_images/3362699-232df5d6fd21000a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

在ContextLoaderListener中的contextInitialized方法
**[java]** [view plain](http://blog.csdn.net/zjw10wei321/article/details/40145241#) [copy](http://blog.csdn.net/zjw10wei321/article/details/40145241#)

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

初始化root跟web上下文,initWebApplicationContext方法在其父类ContextLoader中提供实现。

ContextLoader中initWebApplicationContext方法初始化根上下文


/** 
     * 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) {  
        //这里判断是否在ServletContext中存在上下文,如果有,说明已载入过或配置文件出错,可以从错误信息中看出  
        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.context == null) {  
                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.  
                        // 这里载入根上下文的父上下文     
                        ApplicationContext parent = loadParentContext(servletContext);  
                        cwac.setParent(parent);  
                    }  
                     //这里从web.xml中取得相关的初始化参数,对WebApplicationContext进行初始化  
                    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 (ccl != null) {  
                currentContextPerThread.put(ccl, this.context);  
            }  
  
            if (logger.isDebugEnabled()) {  
                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +  
                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");  
            }  
            if (logger.isInfoEnabled()) {  
                long elapsedTime = System.currentTimeMillis() - startTime;  
                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");  
            }  
  
            return this.context;  
        }  
        catch (RuntimeException ex) {  
            logger.error("Context initialization failed", ex);  
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);  
            throw ex;  
        }  
        catch (Error err) {  
            logger.error("Context initialization failed", err);  
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);  
            throw err;  
        }  
    }  

根据提供的servlet上下文去初始化Spring的web应用上下文,在构造时使用当前应用上下文或者在web.xml中配置参数contextClass和contextConfigLocation去创建新的上下文。

先判断是否在ServletContext中存在root上下文,如果有,说明已载入过或配置文件出错,可以从错误信息中看出。
通过createWebApplicationContext方法创建web应用上下文,此上下文必定是实现了ConfigurableWebApplicationContext接口,在设置parent for root web application context,在configureAndRefreshWebApplicationContext方法里构造bean工厂和容器里bean的创建,这里就不描述了,下次专门研究这块,最后将跟上下文存入servletContext里,同时根web应用上下文存入到currentContextPerThread,可供后续取出当前上下文,currentContextPerThread = new ConcurrentHashMap<ClassLoader, WebApplicationContext>(1);。

ContextLoader中createWebApplicationContext方法创建根上下文


/** 
     * 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 subclasses to perform custom modifications to the context. 
     * @param sc current servlet context 
     * @return the root WebApplicationContext 
     * @see ConfigurableWebApplicationContext 
     */  
    protected WebApplicationContext createWebApplicationContext(ServletContext sc) {  
        //这里需要确定我们载入的根WebApplication的类型,  
        //由在web.xml中配置的contextClass中配置的参数, 如果没有使用默认的。   
        Class<?> contextClass = determineContextClass(sc);  
        //contextClass必须实现ConfigurableWebApplicationContext,否则抛异常  
        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {  
            throw new ApplicationContextException("Custom context class [" + contextClass.getName() +  
                    "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");  
        }  
        //初始化WebApplication,强转成ConfigurableWebApplicationContext  
        return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);  
    }  

初始化根上下文,
最后返回值需强转成ConfigurableWebApplicationContext。

ContextLoader中determineContextClass方法找到根上下文的Class类型


/** 
     * 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);  
            }  
        }  
    }  

Web.xml中配置了contextClass就取其值,但必须是实现ConfigurableWebApplicationContext,
没有的就取默认值XmlWebApplicationContext。

ContextClass默认值和ContextLoader.properties如下:


/** 
     * Name of the class path resource (relative to the ContextLoader class) 
     * that defines ContextLoader's default strategy names. 
     */  
    private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";  
  
  
    private static final Properties defaultStrategies;  
  
    static {  
        // Load default strategy implementations from properties file.  
        // This is currently strictly internal and not meant to be customized  
        // by application developers.  
        try {  
            ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);  
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);  
        }  
        catch (IOException ex) {  
            throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());  
        }  
    }  
# Default WebApplicationContext implementation class for ContextLoader.  
# Used as fallback when no explicit context implementation has been specified as context-param.  
# Not meant to be customized by application developers.  
  
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext  

其中loadParentContext


/** 
     * 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;  
    }  

根据在web.xml中配置的locatorFactorySelector和parentContextKey来给根web应用上下设置父上下文,如果没配置的话,父上下文为空。
加载父上下文的主要原因是允许多重root web application contexts作为可共享的ERA context的子节点,或者对EJB可见的去交替共享同样的父上下文。For pure web applications, there is usually no need to worry about having a parent context to the root web application context。这句话明确告诉我们,对于纯粹的Web应用,通常不用担心root web application context的父上下文,也就是没有,为null。

在应用程序如何获取 WebApplicationContext 有多种方式,最简单的就是
1.WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
当前应用的WebApplicationContext就保存在 ContextLoader的currentContextPerThread属性当中

2.基于ServletContext上下文获取的方式
ServletContext sc = request.getSession().getServletContext();
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(sc);
WebApplicationContext wac1 = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

3.还有一些更合适的,基于spring提供的抽象类或者接口,在初始化Bean时注入ApplicationContext
3.1:继承自抽象类ApplicationObjectSupport
说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。
Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

3.2:继承自抽象类WebApplicationObjectSupport
说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

3.3:实现接口ApplicationContextAware
说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。

总结:Context结构复杂,parentContext结构的作用,及如何的去加载bean工厂的逻辑原理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,287评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,346评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,277评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,132评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,147评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,106评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,019评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,862评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,301评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,521评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,682评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,405评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,996评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,651评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,803评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,674评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,563评论 2 352

推荐阅读更多精彩内容