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ò)程妄荔,依賴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ū)懰赖模┶寤骸H绻麤](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)系作者
  • 序言:七十年代末航背,一起剝皮案震驚了整個(gè)濱河市喉悴,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌玖媚,老刑警劉巖箕肃,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異今魔,居然都是意外死亡勺像,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)错森,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)吟宦,“玉大人,你說(shuō)我怎么就攤上這事涩维⊙晷眨” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)辰狡。 經(jīng)常有香客問(wèn)我锋叨,道長(zhǎng),這世上最難降的妖魔是什么宛篇? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任娃磺,我火速辦了婚禮,結(jié)果婚禮上叫倍,老公的妹妹穿的比我還像新娘偷卧。我一直安慰自己,他們只是感情好吆倦,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布听诸。 她就那樣靜靜地躺著,像睡著了一般蚕泽。 火紅的嫁衣襯著肌膚如雪晌梨。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,631評(píng)論 1 305
  • 那天须妻,我揣著相機(jī)與錄音仔蝌,去河邊找鬼。 笑死荒吏,一個(gè)胖子當(dāng)著我的面吹牛敛惊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绰更,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼瞧挤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了儡湾?” 一聲冷哼從身側(cè)響起特恬,我...
    開(kāi)封第一講書(shū)人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎徐钠,沒(méi)想到半個(gè)月后鸵鸥,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡丹皱,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了宋税。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片摊崭。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖杰赛,靈堂內(nèi)的尸體忽然破棺而出呢簸,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布根时,位于F島的核電站瘦赫,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蛤迎。R本人自食惡果不足惜确虱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望替裆。 院中可真熱鬧校辩,春花似錦、人聲如沸辆童。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)把鉴。三九已至故黑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間庭砍,已是汗流浹背场晶。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留逗威,地道東北人峰搪。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像凯旭,于是被迫代替她去往敵國(guó)和親概耻。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容