Spring在web容器中的啟動(dòng)過(guò)程

spring容器的啟動(dòng)過(guò)程是什么?

spring在web容器中,啟動(dòng)過(guò)程是Servlet 容器對(duì)spring環(huán)境的構(gòu)造,初始化,裝配的過(guò)程。

spring的啟動(dòng)過(guò)程

1.通過(guò)ContextLoaderListener監(jiān)聽(tīng)作為啟動(dòng)spring的入口

啟動(dòng)必要條件:在web.xml中配置
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
ContextLoaderListener(spring中的類(lèi))繼承ContextLoader(spring中的類(lèi)),并實(shí)現(xiàn)ServletContextListener(servlet中的接口),ServletContextListener監(jiān)聽(tīng)ServletContext,當(dāng)容器啟動(dòng)時(shí),會(huì)觸發(fā)ServletContextEvent事件,該事件由ServletContextListener來(lái)處理,啟動(dòng)初始化ServletContext時(shí),調(diào)用contextInitialized方法。而ContextLoaderListener實(shí)現(xiàn)了ServletContextListener,所以,當(dāng)容器啟動(dòng)時(shí),觸發(fā)ServletContextEvent事件,讓ContextLoaderListener執(zhí)行實(shí)現(xiàn)方法contextInitialized(ServletContextEvent sce);
這部分源碼為:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
      public void contextInitialized(ServletContextEvent event) {
        this.contextLoader = createContextLoader();
        if (this.contextLoader == null) {
            this.contextLoader = this;
        }
        this.contextLoader.initWebApplicationContext(event.getServletContext());
    }
}
RBTF87XC7MOV_2J_BK(7L8W.png
2.通過(guò)initWebApplicationContext方法來(lái)初始化WebApplicationContext

WebApplicationContext是spring中的上下文。它的作用等同于Servlet中的ServletContext。
(部分注釋源碼被我刪掉)

public WebApplicationContext initWebApplicationContext(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!");
        }
        try {
            if (this.context == null) {
                this.context = createWebApplicationContext(servletContext);
            }
            if (this.context instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
                if (!cwac.isActive()) {
                    if (cwac.getParent() == null) {
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    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;
        }
    }

initWebApplicationContext(ServletContext servletContext)方法是ContextLoader中的方法。它的作用是制作一個(gè)WebApplicationContext上下文,并將這個(gè)上下文保存在servletContext中,并保存在當(dāng)前ContextLoader實(shí)例中。

3.如何初始化WebApplicationContext

上面源碼中的
this.context = createWebApplicationContext(servletContext);
用來(lái)制造一個(gè)WebApplicationContext,制造的過(guò)程,依賴(lài)ServletContext。

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
        Class<?> contextClass = determineContextClass(sc);
        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
                    "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
        }
        return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

通過(guò)determineContextClass(ServletContext servletContext)方法獲取需要實(shí)例化的context類(lèi)的class,通過(guò)BeanUtils.instantiateClass(contextClass)將這個(gè)class用反射的手段實(shí)例化WebApplicationContext 。
那么determineContextClass怎樣來(lái)確定實(shí)例化那個(gè)context類(lèi)那?(spring有很多的context類(lèi)實(shí)現(xiàn)了WebApplicationContext ,當(dāng)然這個(gè)context類(lèi)也可以是我們自己寫(xiě)的,具體實(shí)例化那個(gè)類(lèi),在web.xml中配置)

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

從上面的代碼可以看出,先從servletContext中找我們?cè)趙eb.xml中有沒(méi)有配置要實(shí)例化那個(gè)上下文context,如果配置了

<context-param>   

  <param-name>contextClass</param-name>   

  <param-value>rg.springframework.web.context.support.StaticWebApplicationContext</param-value>   

  </context-param> 

那么將實(shí)例化StaticWebApplicationContext這個(gè)上下文。注意:這個(gè)地方的param-name必須是contextClass(約定成俗的,其實(shí)就是是程序?qū)懰赖模?。如果沒(méi)有這個(gè)配置,那么程序?qū)⒄业揭粋€(gè)叫ContextLoader.properties的配置文件,這個(gè)配置文件注明了一個(gè)默認(rèn)的上下文:XmlWebApplicationContext。這個(gè)XmlWebApplicationContext實(shí)例化的過(guò)程是制造一個(gè)ResourcePatternResolver的實(shí)例,這個(gè)實(shí)例將會(huì)在后面的spring啟動(dòng)過(guò)程中起到關(guān)鍵作用。
最后流程圖:


20151203174349465 (1).png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容