Spring Ioc 源碼分析(三)--loadBeanDefinitions

上一篇博客說到倍宾,ApplicationContext將解析BeanDefinition的工作委托給BeanDefinitionReader組件陡厘,這篇就接著分析一下BeanDefinition的解析過程惊楼。

loadBeanDefinitions: 源碼閱讀


入口是loadBeanDefinitions方法

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) 
throws IOException {
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String configLocation : configLocations) {
                reader.loadBeanDefinitions(configLocation);
            }
        }
}

這是解析過程最外圍的代碼带族,首先要獲取到配置文件的路徑草冈,這在之前已經(jīng)完成了棺蛛。
然后將每個(gè)配置文件的路徑藏畅,作為參數(shù)傳給BeanDefinitionReader的loadBeanDefinitions方法里

public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
        return loadBeanDefinitions(location, null);
}

這個(gè)方法又調(diào)用了重載方法

public int loadBeanDefinitions(String location, Set<Resource> actualResources) 
throws BeanDefinitionStoreException {
        ResourceLoader resourceLoader = getResourceLoader();
        if (resourceLoader == null) {
            throw new BeanDefinitionStoreException(
                    "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
        }

        if (resourceLoader instanceof ResourcePatternResolver) {
            // Resource pattern matching available.
            try {
                Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
                int loadCount = loadBeanDefinitions(resources);
                if (actualResources != null) {
                    for (Resource resource : resources) {
                        actualResources.add(resource);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
                }
                return loadCount;
            }
            catch (IOException ex) {
                throw new BeanDefinitionStoreException(
                        "Could not resolve bean definition resource pattern [" + location + "]", ex);
            }
        }
        else {
            // Can only load single resources by absolute URL.
            Resource resource = resourceLoader.getResource(location);
            int loadCount = loadBeanDefinitions(resource);
            if (actualResources != null) {
                actualResources.add(resource);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
            }
            return loadCount;
        }
    }

首先getResourceLoader()的實(shí)現(xiàn)的前提條件是因?yàn)閄mlBeanDefinitionReader在實(shí)例化的時(shí)候已經(jīng)確定了創(chuàng)建了實(shí)例ResourceLoader實(shí)例, 代碼位于 AbstractBeanDefinitionReader

protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {   
     Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); 
     this.registry = registry;   
     // Determine ResourceLoader to use.  
     if (this.registry instanceof ResourceLoader) {     
         this.resourceLoader = (ResourceLoader) this.registry;   
      }  else {      
         this.resourceLoader = new PathMatchingResourcePatternResolver();  
      }   
     // Inherit Environment if possible   
     if (this.registry instanceof EnvironmentCapable) {      
          this.environment = ((EnvironmentCapable)this.registry).getEnvironment();  
      }  else {      
          this.environment = new StandardEnvironment(); 
      }
}

這個(gè)方法比較長敷硅,BeanDefinitionReader不能直接加載配置文件,需要把配置文件封裝成Resource愉阎,然后才能調(diào)用重載方法loadBeanDefinitions()绞蹦。所以這個(gè)方法其實(shí)就是2段,第一部分是委托ResourceLoader將配置文件封裝成Resource榜旦,第二部分是調(diào)用loadBeanDefinitions()幽七,對(duì)Resource進(jìn)行解析

而這里的ResourceLoader,就是前面的XmlWebApplicationContext溅呢,因?yàn)锳pplicationContext接口澡屡,是繼承自ResourceLoader接口的

Resource也是一個(gè)接口體系,在web環(huán)境下咐旧,這里就是ServletContextResource

接下來進(jìn)入重載方法loadBeanDefinitions()

public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
        Assert.notNull(resources, "Resource array must not be null");
        int counter = 0;
        for (Resource resource : resources) {
            counter += loadBeanDefinitions(resource);
        }
        return counter;
    }

這里就不用說了挪蹭,就是把每一個(gè)Resource作為參數(shù),繼續(xù)調(diào)用重載方法休偶。讀spring源碼梁厉,會(huì)發(fā)現(xiàn)重載方法特別多。

public int loadBeanDefinitions(Resource resource)  throws
 BeanDefinitionStoreException {
        return loadBeanDefinitions(new EncodedResource(resource));
}

還是重載方法踏兜,不過這里對(duì)傳進(jìn)來的Resource又進(jìn)行了一次封裝词顾,變成了編碼后的Resource。

public int loadBeanDefinitions(EncodedResource encodedResource) 
throws BeanDefinitionStoreException {
        Assert.notNull(encodedResource, "EncodedResource must not be null");
        if (logger.isInfoEnabled()) {
            logger.info("Loading XML bean definitions from " + encodedResource.getResource());
        }

        Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
        if (currentResources == null) {
            currentResources = new HashSet<EncodedResource>(4);
            this.resourcesCurrentlyBeingLoaded.set(currentResources);
        }
        if (!currentResources.add(encodedResource)) {
            throw new BeanDefinitionStoreException(
                    "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
        }
        try {
            InputStream inputStream = encodedResource.getResource().getInputStream();
            try {
                InputSource inputSource = new InputSource(inputStream);
                if (encodedResource.getEncoding() != null) {
                    inputSource.setEncoding(encodedResource.getEncoding());
                }
                return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
            }
            finally {
                inputStream.close();
            }
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "IOException parsing XML document from " + encodedResource.getResource(), ex);
        }
        finally {
            currentResources.remove(encodedResource);
            if (currentResources.isEmpty()) {
                this.resourcesCurrentlyBeingLoaded.remove();
            }
        }
    }

這個(gè)就是loadBeanDefinitions()的最后一個(gè)重載方法碱妆,比較長肉盹,可以拆看來看。

Assert.notNull(encodedResource, "EncodedResource must not be null");
        if (logger.isInfoEnabled()) {
            logger.info("Loading XML bean definitions from " + encodedResource.getResource());
        }

        Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
        if (currentResources == null) {
            currentResources = new HashSet<EncodedResource>(4);
            this.resourcesCurrentlyBeingLoaded.set(currentResources);
        }
        if (!currentResources.add(encodedResource)) {
            throw new BeanDefinitionStoreException(
                    "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
        }

這第一部分疹尾,是處理線程相關(guān)的工作上忍,把當(dāng)前正在解析的Resource,設(shè)置為當(dāng)前Resource纳本。

try {
            InputStream inputStream = encodedResource.getResource().getInputStream();
            try {
                InputSource inputSource = new InputSource(inputStream);
                if (encodedResource.getEncoding() != null) {
                    inputSource.setEncoding(encodedResource.getEncoding());
                }
                return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
            }
            finally {
                inputStream.close();
            }
        }

這里是第二部分窍蓝,是核心,首先把Resource還原為InputStream繁成,然后調(diào)用實(shí)際解析的方法doLoadBeanDefinitions()吓笙。可以看到,這種命名方式是很值得學(xué)習(xí)的巾腕,一種業(yè)務(wù)方法面睛,比如parse()絮蒿,可能需要做一些外圍的工作,然后實(shí)際解析的方法叁鉴,可以命名為doParse()土涝。這種doXXX()的命名方法,在很多開源框架中都有應(yīng)用幌墓,比如logback等但壮。
接下來就看一下這個(gè)doLoadBeanDefinitions()方法

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {
        try {
            Document doc = doLoadDocument(inputSource, resource);return registerBeanDefinitions(doc, resource);
            return registerBeanDefinitions(doc, resource);
        }
        catch (BeanDefinitionStoreException ex) {
            throw ex;
        }
        catch (SAXParseException ex) {
            throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                    "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
        }
        catch (SAXException ex) {
            throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                    "XML document from " + resource + " is invalid", ex);
        }
        catch (ParserConfigurationException ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "Parser configuration exception parsing XML from " + resource, ex);
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "IOException parsing XML document from " + resource, ex);
        }
        catch (Throwable ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "Unexpected exception parsing XML document from " + resource, ex);
        }
    }

拋開異常處理:核心代碼如下:

 Document doc = doLoadDocument(inputSource, resource);
 return  registerBeanDefinitions(doc, resource);

doLoadDocument方法將InputStream讀取成標(biāo)準(zhǔn)的Document對(duì)象,然后調(diào)用registerBeanDefinitions()克锣,進(jìn)行解析工作茵肃。

protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {   
    return this.documentLoader.loadDocument(inputSource,  
                                            getEntityResolver(), this.errorHandler,  
                                            getValidationModeForResource(resource),  
                                            isNamespaceAware());
}

接下來就看一下這個(gè)核心方法registerBeanDefinitions

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
        //創(chuàng)建的其實(shí)是DefaultBeanDefinitionDocumentReader 的實(shí)例腔长,利用反射創(chuàng)建的袭祟。
        BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
        documentReader.setEnvironment(this.getEnvironment());
        int countBefore = getRegistry().getBeanDefinitionCount();
        documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
        return getRegistry().getBeanDefinitionCount() - countBefore;
}

這里注意兩點(diǎn) :

1.Document對(duì)象
首先這個(gè)Document對(duì)象,是W3C定義的標(biāo)準(zhǔn)XML對(duì)象捞附,跟spring無關(guān)巾乳。其次這個(gè)registerBeanDefinitions方法,我覺得命名有點(diǎn)誤導(dǎo)性鸟召。因?yàn)檫@個(gè)時(shí)候?qū)嶋H上解析還沒有開始胆绊,怎么直接就注冊(cè)了呢。比較好的命名欧募,我覺得可以是parseAndRegisterBeanDefinitions()压状。
2.documentReader的創(chuàng)建時(shí)使用反射創(chuàng)建的,代碼如下

protected BeanDefinitionDocumentReader    
 createBeanDefinitionDocumentReader() {   
          return BeanDefinitionDocumentReader.class.cast(BeanUtils.
            instantiateClass(this.documentReaderClass));
}

instantiateClass方法中傳入了一個(gè)Class類型的參數(shù)跟继。追溯發(fā)現(xiàn)下述代碼:

private Class<?> documentReaderClass = 
DefaultBeanDefinitionDocumentReader.class;

所以創(chuàng)建的documentReaderClass是DefaultBeanDefinitionDocumentReader類的實(shí)例种冬。
接下來就進(jìn)入BeanDefinitionDocumentReader 中定義的registerBeanDefinitions()方法看看

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
        this.readerContext = readerContext;
        logger.debug("Loading bean definitions");
        Element root = doc.getDocumentElement();
        doRegisterBeanDefinitions(root);
    }

處理完外圍事務(wù)之后,進(jìn)入doRegisterBeanDefinitions()方法舔糖,這種命名規(guī)范娱两,上文已經(jīng)介紹過了

protected void doRegisterBeanDefinitions(Element root) {
        String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
        if (StringUtils.hasText(profileSpec)) {
            Assert.state(this.environment != null, "environment property must not be null");
            String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            if (!this.environment.acceptsProfiles(specifiedProfiles)) {
                return;
            }
        }
        // any nested <beans> elements will cause recursion in this method. In
        // order to propagate and preserve <beans> default-* attributes correctly,
        // keep track of the current (parent) delegate, which may be null. Create
        // the new (child) delegate with a reference to the parent for fallback purposes,
        // then ultimately reset this.delegate back to its original (parent) reference.
        // this behavior emulates a stack of delegates without actually necessitating one.
        BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createHelper(readerContext, root, parent);
        preProcessXml(root);
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);
        this.delegate = parent;
}

這個(gè)方法也比較長,拆開來看

String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
        if (StringUtils.hasText(profileSpec)) {
            Assert.state(this.environment != null, "environment property must not be null");
            String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            if (!this.environment.acceptsProfiles(specifiedProfiles)) {
                return;
            }
}

如果配置文件中元素金吗,配有profile屬性十兢,就會(huì)進(jìn)入這一段,不過一般都是不會(huì)的

        BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createHelper(readerContext, root, parent);
        preProcessXml(root);
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);
        this.delegate = parent;

然后這里創(chuàng)建了BeanDefinitionParserDelegate對(duì)象摇庙,preProcessXml()和postProcessXml()都是空方法旱物,核心就是parseBeanDefinitions()方法。這里又把BeanDefinition解析和注冊(cè)的工作卫袒,委托給了BeanDefinitionParserDelegate對(duì)象异袄,在parseBeanDefinitions()方法中完成
總的來說,解析工作的委托鏈?zhǔn)沁@樣的:ClassPathXmlApplicationContext玛臂,XmlBeanDefinitionReader烤蜕,DefaultBeanDefinitionDocumentReader封孙,BeanDefinitionParserDelegate
ClassPathXmlApplicationContext作為最外圍的組件,發(fā)起解析的請(qǐng)求
XmlBeanDefinitionReader將配置文件路徑封裝為Resource讽营,讀取出w3c定義的Document對(duì)象虎忌,然后委托給DefaultBeanDefinitionDocumentReader
DefaultBeanDefinitionDocumentReader就開始做實(shí)際的解析工作了,但是涉及到bean的具體解析橱鹏,它還是會(huì)繼續(xù)委托給BeanDefinitionParserDelegate來做膜蠢。
接下來在parseBeanDefinitions()方法中發(fā)生了什么,以及BeanDefinitionParserDelegate類完成的工作莉兰,在下一篇博客中繼續(xù)介紹将饺。

博客搬家:大坤的個(gè)人博客
歡迎評(píng)論哦~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市涎嚼,隨后出現(xiàn)的幾起案子席噩,更是在濱河造成了極大的恐慌,老刑警劉巖捶朵,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜘矢,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡综看,警方通過查閱死者的電腦和手機(jī)品腹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來红碑,“玉大人舞吭,你說我怎么就攤上這事∥錾海” “怎么了羡鸥?”我有些...
    開封第一講書人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長唾琼。 經(jīng)常有香客問我兄春,道長,這世上最難降的妖魔是什么锡溯? 我笑而不...
    開封第一講書人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任赶舆,我火速辦了婚禮,結(jié)果婚禮上祭饭,老公的妹妹穿的比我還像新娘芜茵。我一直安慰自己,他們只是感情好倡蝙,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開白布九串。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪猪钮。 梳的紋絲不亂的頭發(fā)上品山,一...
    開封第一講書人閱讀 49,929評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音烤低,去河邊找鬼肘交。 笑死,一個(gè)胖子當(dāng)著我的面吹牛扑馁,可吹牛的內(nèi)容都是我干的涯呻。 我是一名探鬼主播,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼腻要,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼复罐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起雄家,我...
    開封第一講書人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤效诅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后咳短,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體填帽,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蛛淋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年咙好,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片褐荷。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡勾效,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出叛甫,到底是詐尸還是另有隱情层宫,我是刑警寧澤,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布其监,位于F島的核電站萌腿,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏抖苦。R本人自食惡果不足惜毁菱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望锌历。 院中可真熱鬧贮庞,春花似錦、人聲如沸究西。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至遮斥,卻和暖如春峦失,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背术吗。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來泰國打工宠进, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人藐翎。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓材蹬,卻偏偏與公主長得像,于是被迫代替她去往敵國和親吝镣。 傳聞我的和親對(duì)象是個(gè)殘疾皇子堤器,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

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