漫談Spring的啟動(dòng)與初始化(二)

上一篇關(guān)于Spring是如何啟動(dòng)的文章鸭栖,主要是分析了從Tomcat啟動(dòng)到web.xml文件加載,再到通過ContextLoaderListener監(jiān)聽器開始初始化WebApplicationContext這個(gè)過程误墓,如果不熟悉可以參考這篇-漫談Spring的啟動(dòng)與初始化(一),但是上一篇還沒有分析到Spring容器是如何通過web.xml里面配置的contextConfigLocation參數(shù)和Spring容器的配置文件applicationContext.xml來初始化Spring户魏,本文著力于解決這個(gè)疑惑饮戳。

initWebApplicationContext方法

當(dāng)ContextLoaderListener監(jiān)聽到ServletContext初始化事件的時(shí)候就會(huì)調(diào)用ContextLoaderinitWebApplicationContext方法闲孤,這個(gè)方法完成了很多的工作谆级,其中便有下面這段關(guān)鍵代碼,源碼如下:


    private WebApplicationContext context;
    public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        ...
        if(this.context == null) {
            //如果context為null就開始創(chuàng)建WebApplicationContext
            this.context = this.createWebApplicationContext(servletContext);
        }
        ...
    }

createWebApplicationContext方法

下面進(jìn)入該方法崭放,源碼如下:

    protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
        Class contextClass = this.determineContextClass(sc);
        if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
        } else {
            //根據(jù)類返回實(shí)例
            return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
        }
    }

其中determineContextClass(sc)方法是用來尋找實(shí)現(xiàn)WebApplicationContext接口的類哨苛,實(shí)現(xiàn)方法如下:

    protected Class<?> determineContextClass(ServletContext servletContext) {
        //關(guān)鍵代碼一:
        String contextClassName = servletContext.getInitParameter("contextClass");
        if(contextClassName != null) {
            try {
                return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
            } catch (ClassNotFoundException var4) {
                throw new ApplicationContextException("Failed to load custom context class [" + contextClassName + "]", var4);
            }
        } else {
            //關(guān)鍵代碼二:
            contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());

            try {
                return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
            } catch (ClassNotFoundException var5) {
                throw new ApplicationContextException("Failed to load default context class [" + contextClassName + "]", var5);
            }
        }
    }

上面這兩行代碼就是決定返回的Class:如果開發(fā)人員在web.xml中配置了一個(gè)參數(shù)名為contextClass,值為WebApplicationContext接口實(shí)現(xiàn)類币砂,那getInitParameter("contextClass")就會(huì)返回這個(gè)配置的實(shí)現(xiàn)類Class建峭;如果沒有配置,也就是contextClassName==null决摧,那么通過defaultStrategies.getProperty(...)則會(huì)返回Spring默認(rèn)的實(shí)現(xiàn)類XmlWebApplicationContext亿蒸。可能有同學(xué)會(huì)好奇為什么是這個(gè)掌桩,這個(gè)類是從哪兒來的边锁。
我們回頭在ContextLoader這個(gè)類中最下面可以看到有這么幾行靜態(tài)代碼段,在類一加載的時(shí)候執(zhí)行波岛,如下:

public class ContextLoader {
    private static final Properties defaultStrategies;
    static {
        try {
            ClassPathResource ex = new ClassPathResource("ContextLoader.properties", ContextLoader.class);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(ex);
        } catch (IOException var1) {
            throw new IllegalStateException("Could not load \'ContextLoader.properties\': " + var1.getMessage());
        }

        currentContextPerThread = new ConcurrentHashMap(1);
    }
}

ContextLoader.class的同一個(gè)包下面茅坛,可以找到這個(gè)配置文件,其中只有一行配置如下:

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

XmlWebApplicationContext這個(gè)類就是WebApplicationContext這個(gè)接口最終的實(shí)現(xiàn)類则拷,也是Spring啟動(dòng)時(shí)默認(rèn)使用的類贡蓖。其實(shí)還有一些實(shí)現(xiàn)類,讓我們自己去加載applicationContext.xml煌茬,比如ClassPathXmlApplicationContext斥铺。
這樣在上述的createWebApplicationContext方法中,我們拿到的就是XmlWebApplicationContext.class坛善,然后通過BeanUtils.instantiateClass(contextClass)方法根據(jù)類名創(chuàng)建對應(yīng)實(shí)例晾蜘,并且進(jìn)行強(qiáng)制轉(zhuǎn)換得到ConfigurableWebApplicationContext接口的實(shí)例,因?yàn)?code>XmlWebApplicationContext是后者的實(shí)現(xiàn)類眠屎,所以這樣轉(zhuǎn)換是沒問題的(當(dāng)然沒問題哈哈)剔交。
那么createWebApplicationContext方法分析到此為止。

我們繼續(xù)看initWebApplicationContext方法中下面這段代碼的最后一行:

    if(this.context == null) {
        //如果context為null就開始創(chuàng)建WebApplicationContext
        this.context = this.createWebApplicationContext(servletContext);
    }
    if(this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext err = (ConfigurableWebApplicationContext)this.context;
        if(!err.isActive()) {
            ...
            //關(guān)鍵代碼:配置和刷新WebApplicationContext改衩,這里其實(shí)就是XmlWebApplicationContext了
            this.configureAndRefreshWebApplicationContext(err, servletContext);
        }
    }

configureAndRefreshWebApplicationContext方法

在上面代碼中我們通過XmlWebApplicationContext類創(chuàng)建了WebApplicationContext的實(shí)例岖常,本節(jié)方法則是為該實(shí)例設(shè)置一些配置信息和創(chuàng)建各種bean。我們重點(diǎn)關(guān)注下面幾行代碼:

    protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
        ...
        wac.setServletContext(sc);
        //關(guān)鍵代碼一:在ServletContext中獲取contextConfigLocation值燎字,查找配置文件地址
        configLocationParam = sc.getInitParameter("contextConfigLocation");
        if(configLocationParam != null) {
            wac.setConfigLocation(configLocationParam);
        }
        ...
        //關(guān)鍵代碼二:刷新XmlWebApplicationContext
        wac.refresh();
    }

在Spring的項(xiàng)目中腥椒,經(jīng)常要在web.xml中配置contextConfigLocation的參數(shù),我們對于下面的幾行xml代碼應(yīng)該也很熟悉候衍,它設(shè)置了Spring容器配置文件的路徑:

    <!-- Context ConfigLocation -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param>

既然是在web.xml中配置的這些參數(shù)笼蛛,為什么是在ServletContext中去取呢?在上一篇文章中分析過蛉鹿,Tomcat在加載web.xml文件時(shí)滨砍,會(huì)最終將該配置文件的配置屬性參數(shù)以鍵值對的形式存放在每個(gè)web應(yīng)用對應(yīng)的ServletContext中,這樣我們在web應(yīng)用中的任何地方都可以拿到該參數(shù)值(后面還會(huì)提到ServletContext其他的使用場景)妖异。
當(dāng)然惋戏,如果我們沒有在web.xml中配置該參數(shù)的話,XmlWebApplicationContext類也是有默認(rèn)值的他膳,如下:

    public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
        public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
        public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
        public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
    }

到這里响逢,配置文件信息拿到了,再就是wac.refresh()方法了棕孙,這個(gè)方法具體實(shí)現(xiàn)在AbstractApplicationContext類中舔亭,進(jìn)入該方法:

    public void refresh() throws BeansException, IllegalStateException {
        Object var1 = this.startupShutdownMonitor;
        synchronized(this.startupShutdownMonitor) {
           //容器預(yù)先準(zhǔn)備,記錄容器啟動(dòng)時(shí)間和標(biāo)記
          prepareRefresh();
          //創(chuàng)建bean工廠蟀俊,里面實(shí)現(xiàn)了BeanDefinition的裝載
          ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
          //配置bean工廠的上下文信息钦铺,如類裝載器等
          prepareBeanFactory(beanFactory);
          try {
            //在BeanDefinition被裝載后,提供一個(gè)修改BeanFactory的入口
            postProcessBeanFactory(beanFactory);
            //在bean初始化之前肢预,提供對BeanDefinition修改入口矛洞,PropertyPlaceholderConfigurer在這里被調(diào)用
            invokeBeanFactoryPostProcessors(beanFactory);
            //注冊各種BeanPostProcessors,用于在bean被初始化時(shí)進(jìn)行攔截烫映,進(jìn)行額外初始化操作
            registerBeanPostProcessors(beanFactory);
            //初始化MessageSource
            initMessageSource();
            //初始化上下文事件廣播
            initApplicationEventMulticaster();
            //模板方法
            onRefresh();
            //注冊監(jiān)聽器
            registerListeners();
            //初始化所有未初始化的非懶加載的單例Bean
            finishBeanFactoryInitialization(beanFactory);
            //發(fā)布事件通知
            finishRefresh();
            } catch (BeansException var5) {
                if(this.logger.isWarnEnabled()) {
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var5);
                }
                this.destroyBeans();
                this.cancelRefresh(var5);
                throw var5;
            }

        }
    }

這個(gè)方法里面就是IOC容器初始化的大致步驟了沼本。

after configureAndRefresh

在IOC容器初始化之后,也就是configureAndRefreshWebApplicationContext方法執(zhí)行結(jié)束后有一行代碼如下:

        //關(guān)鍵代碼:
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

可以看到窑邦,這里初始化后的context被存放到了servletContext中擅威,具體的就是存到了一個(gè)Map變量中,key值就是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE這個(gè)常量冈钦。這個(gè)key常量在WebApplicationContext接口中設(shè)置的郊丛,如下:

public interface WebApplicationContext extends ApplicationContext {
    //org.springframework.web.context.WebApplicationContext.ROOT
    String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
}

另外,我們也可以使用Spring的WebApplicationContextUtils工具類獲取這個(gè)WebApplicationContext(不過這里request獲取ServletContext是有限制的瞧筛,要求servlet-api.jar 包的版本是在3.0以上)方式如下:

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

到這里Spring的啟動(dòng)與初始化應(yīng)該就結(jié)束了厉熟,這里面要理清ServletContext和Spring容器的關(guān)系,整個(gè)Spring容器被放置在ServletContext這樣一個(gè)類似于Map的結(jié)構(gòu)中较幌。ServletContext 從字面上理解也是Servlet的容器揍瑟,被 Servlet 程序間接用來與外層 Web 容器通信,例如寫日志乍炉,轉(zhuǎn)發(fā)請求等绢片。每一個(gè) Web 應(yīng)用程序含有一個(gè)Context 滤馍,被Web 應(yīng)用內(nèi)的各個(gè)程序共享。因?yàn)镃ontext 可以用來保存資源并且共享底循,所以ServletContext 的常用場景是Web級應(yīng)用緩存---- 把不經(jīng)常更改的內(nèi)容讀入內(nèi)存巢株,所以服務(wù)器響應(yīng)請求的時(shí)候就不需要進(jìn)行慢速的磁盤I/O 了。

參考

深入理解Spring系列之七:web應(yīng)用自動(dòng)裝配Spring配置

-EOF-

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末熙涤,一起剝皮案震驚了整個(gè)濱河市阁苞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌祠挫,老刑警劉巖那槽,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異等舔,居然都是意外死亡骚灸,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進(jìn)店門慌植,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逢唤,“玉大人,你說我怎么就攤上這事涤浇”钆海” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵只锭,是天一觀的道長著恩。 經(jīng)常有香客問我,道長蜻展,這世上最難降的妖魔是什么喉誊? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮纵顾,結(jié)果婚禮上伍茄,老公的妹妹穿的比我還像新娘。我一直安慰自己施逾,他們只是感情好敷矫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著汉额,像睡著了一般曹仗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蠕搜,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天怎茫,我揣著相機(jī)與錄音,去河邊找鬼妓灌。 笑死轨蛤,一個(gè)胖子當(dāng)著我的面吹牛蜜宪,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播祥山,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼端壳,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了枪蘑?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤岖免,失蹤者是張志新(化名)和其女友劉穎岳颇,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體颅湘,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡话侧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了闯参。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瞻鹏。...
    茶點(diǎn)故事閱讀 39,711評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖鹿寨,靈堂內(nèi)的尸體忽然破棺而出新博,到底是詐尸還是另有隱情,我是刑警寧澤脚草,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布赫悄,位于F島的核電站,受9級特大地震影響馏慨,放射性物質(zhì)發(fā)生泄漏埂淮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一写隶、第九天 我趴在偏房一處隱蔽的房頂上張望倔撞。 院中可真熱鬧,春花似錦慕趴、人聲如沸痪蝇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽霹俺。三九已至,卻和暖如春毒费,著一層夾襖步出監(jiān)牢的瞬間丙唧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工觅玻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留想际,地道東北人培漏。 一個(gè)月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像胡本,于是被迫代替她去往敵國和親牌柄。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評論 2 353

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