Spring源碼剖析3:Spring IOC容器的加載過程

本文轉自五月的倉頡 https://www.cnblogs.com/xrq730

本系列文章將整理到我在GitHub上的《Java面試指南》倉庫努溃,更多精彩內容請到我的倉庫里查看

https://github.com/h2pl/Java-Tutorial

喜歡的話麻煩點下Star哈

文章將同步到我的個人博客:

www.how2playlife.com

本文是微信公眾號【Java技術江湖】的《Spring和SpringMVC源碼分析》其中一篇芯杀,本文部分內容來源于網絡,為了把本文主題講得清晰透徹汇荐,也整合了很多我認為不錯的技術博客內容,引用其中了一些比較好的博客文章褂微,如有侵權瓜饥,請聯(lián)系作者。

該系列博文會告訴你如何從spring基礎入手冷溃,一步步地學習spring基礎和springmvc的框架知識钱磅,并上手進行項目實戰(zhàn),spring框架是每一個Java工程師必須要學習和理解的知識點似枕,進一步來說盖淡,你還需要掌握spring甚至是springmvc的源碼以及實現(xiàn)原理,才能更完整地了解整個spring技術體系凿歼,形成自己的知識框架褪迟。

后續(xù)還會有springboot和springcloud的技術專題,陸續(xù)為大家?guī)泶疸荆凑埰诖?/p>

為了更好地總結和檢驗你的學習成果味赃,本系列文章也會提供部分知識點對應的面試題以及參考答案。

如果對本系列文章有什么建議攀唯,或者是有什么疑問的話洁桌,也可以關注公眾號【Java技術江湖】聯(lián)系作者,歡迎你參與本系列博文的創(chuàng)作和修訂侯嘀。

spring ioc 容器的加載流程

1.目標:熟練使用spring另凌,并分析其源碼,了解其中的思想戒幔。這篇主要介紹spring ioc 容器的加載

2.前提條件:會使用debug

3.源碼分析方法:Intellj idea debug 模式下源碼追溯
通過ClassPathXmlApplicationContext 進行xml 件的讀取吠谢,從每個堆棧中讀取程序的運行信息

4.注意:由于Spring的類繼承體系比較復雜,不能全部貼圖,所以只將分析源碼之后發(fā)現(xiàn)的最主要的類繼承結構類圖貼在下方诗茎。

5.關于Spring Ioc
Demo:
我們從demo入手一步步進行代碼追溯工坊。

Spring Ioc Demo


1.定義數(shù)據(jù)訪問接口IUserDao.java

public interface IUserDao {  
    public void InsertUser(String username,String password);
}

2.定義IUserDao.java實現(xiàn)類IUserDaoImpl.java

public class UserDaoImpl implements IUserDao {    
    @Override    
    public void InsertUser(String username, String password) { 
        System.out.println("----UserDaoImpl --addUser----");    
    }
}

3.定義業(yè)務邏輯接口UserService.java

public interface UserService {    
    public void addUser(String username,String password);
}

4.定義UserService.java實現(xiàn)類UserServiceImpl.java

public class UserServiceImpl implements UserService {    
    private     IUserDao  userDao;    //set方法  
    public void  setUserDao(IUserDao  userDao) {        
        this.userDao = userDao;   
    }    
    @Override    
    public void addUser(String username,String password) { 
        userDao.InsertUser(username,password);    
    }
}

bean.xml配置文件

<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         ">  
 <!--id名字自己取,class表示他代表的類敢订,如果在包里的話需要加上包名-->    
 <bean id="userService"  class="UserServiceImpl" >      
        <!--property代表是通過set方法注入,ref的值表示注入的內容-->
        <property  name="userDao"  ref="userDao"/>  
 </bean>    
  <bean id="userDao"  class="UserDaoImpl"/>
</beans>

ApplicationContext 繼承結構


1.頂層接口:ApplicationContext
2.ClassPathXmlApplicationContext實現(xiàn)類繼承AbstractXmlApplication 抽象類
3.AbstractXmlApplication 繼承AbstractRefreshableConfigApplicationContext
4.AbstractRefreshableConfigApplicationContext抽象類繼承AbstractRefreshableApplicationContext
5.AbstractRefreshableApplicationContext 繼承 AbstractApplicationContext
6.AbstractApplicationContext 實現(xiàn)ConfigurableApplicationContext 接口
7.ConfigurableApplicationContext 接口繼承
ApplicationContext接口
總體來說繼承實現(xiàn)結構較深王污,內部使用了大量適配器模式。
以ClassPathXmlApplicationContext為例楚午,繼承類圖如下圖所示:

Spring Ioc容器加載過程源碼詳解


在開始之前昭齐,先介紹一個整體的概念。即spring ioc容器的加載矾柜,大體上經過以下幾個過程:
資源文件定位、解析、注冊叁扫、實例化

1.資源文件定位
其中資源文件定位,一般是在ApplicationContext的實現(xiàn)類里完成的丧荐,因為ApplicationContext接口繼承ResourcePatternResolver 接口,ResourcePatternResolver接口繼承ResourceLoader接口喧枷,ResourceLoader其中的getResource()方法虹统,可以將外部的資源,讀取為Resource類割去。


2.解析DefaultBeanDefinitionDocumentReader窟却,
解析主要是在BeanDefinitionReader中完成的,最常用的實現(xiàn)類是XmlBeanDefinitionReader呻逆,其中的loadBeanDefinitions()方法,負責讀取Resource菩帝,并完成后續(xù)的步驟咖城。ApplicationContext完成資源文件定位之后,是將解析工作委托給XmlBeanDefinitionReader來完成的
解析這里涉及到很多步驟呼奢,最常見的情況宜雀,資源文件來自一個XML配置文件。首先是BeanDefinitionReader握础,將XML文件讀取成w3c的Document文檔辐董。

DefaultBeanDefinitionDocumentReader對Document進行進一步解析。然后DefaultBeanDefinitionDocumentReader又委托給BeanDefinitionParserDelegate進行解析禀综。如果是標準的xml namespace元素简烘,會在Delegate內部完成解析,如果是非標準的xml namespace元素定枷,則會委托合適的NamespaceHandler進行解析最終解析的結果都封裝為BeanDefinitionHolder孤澎,至此解析就算完成。
后續(xù)會進行細致講解欠窒。


3.注冊
然后bean的注冊是在BeanFactory里完成的覆旭,BeanFactory接口最常見的一個實現(xiàn)類是DefaultListableBeanFactory,它實現(xiàn)了BeanDefinitionRegistry接口岖妄,所以其中的registerBeanDefinition()方法型将,可以對BeanDefinition進行注冊這里附帶一提,最常見的XmlWebApplicationContext不是自己持有BeanDefinition的荐虐,它繼承自AbstractRefreshableApplicationContext七兜,其持有一個DefaultListableBeanFactory的字段,就是用它來保存BeanDefinition
所謂的注冊缚俏,其實就是將BeanDefinition的name和實例惊搏,保存到一個Map中贮乳。

剛才說到,最常用的實現(xiàn)DefaultListableBeanFactory恬惯,其中的字段就是beanDefinitionMap向拆,是一個ConcurrentHashMap。
代碼如下:
>1.DefaultListableBeanFactory繼承實現(xiàn)關系

public class DefaultListableBeanFactory
extends 
AbstractAutowireCapableBeanFactory   
implements
ConfigurableListableBeanFactory, 
BeanDefinitionRegistry,
Serializable { 
     // DefaultListableBeanFactory的實例中最終保存了所有注冊的bean    beanDefinitionMap
     /** Map of bean definition objects, keyed by bean name */
     private final Map<String, BeanDefinition> beanDefinitionMap 
     = new ConcurrentHashMap<String, BeanDefinition>(64); 
     //實現(xiàn)BeanDefinitionRegistry中定義的registerBeanDefinition()抽象方法
     public void registerBeanDefinition(String beanName, BeanDefinition    beanDefinition)      throws BeanDefinitionStoreException {
     }

>2.BeanDefinitionRegistry接口

public interface BeanDefinitionRegistry extends AliasRegistry {   
    //定義注冊BeanDefinition實例的抽象方法
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)         throws BeanDefinitionStoreException;

4.實例化


注冊也完成之后酪耳,在BeanFactory的getBean()方法之中浓恳,會完成初始化,也就是依賴注入的過程
大體上的流程就是這樣碗暗。

refresh()方法

1.目標:
這篇記錄debug 追溯源碼的過程颈将,大概分三個篇幅,這是第一篇言疗,現(xiàn)整體了解一下運行流程晴圾,定位資源加載,資源解析噪奄,bean 注冊發(fā)生的位置死姚。
2.記錄結構:
1.調試棧截圖
2.整體流程
3.bean.xml的處理
每段代碼下面有相應的講解

調試棧截圖


每個棧幀中方法的行號都有標明,按照行號追溯源碼勤篮,然后配合教程能夠快速學習都毒。

整體流程


ioc容器實例化代碼

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");

進入代碼中一步步追溯,發(fā)現(xiàn)重要方法:refresh();
如下所示:

public void refresh() throws BeansException, IllegalStateException {

        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();
            //beanFactory實例化方法 單步調試入口
            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }
        }
    }

首先這個方法是同步的碰缔,以避免重復刷新账劲。然后刷新的每個步驟,都放在單獨的方法里金抡,比較清晰瀑焦,可以按順序一個個看

首先是prepareRefresh()方法

protected void prepareRefresh() {
        this.startupDate = System.currentTimeMillis();

        synchronized (this.activeMonitor) {
            this.active = true;
        }

        if (logger.isInfoEnabled()) {
            logger.info("Refreshing " + this);
        }

        // Initialize any placeholder property sources in the context environment
        initPropertySources();

        // Validate that all properties marked as required are resolvable
        // see ConfigurablePropertyResolver#setRequiredProperties
        this.environment.validateRequiredProperties();
    }

這個方法里做的事情不多,記錄了開始時間竟终,輸出日志蝠猬,另外initPropertySources()方法和validateRequiredProperties()方法一般都沒有做什么事。

然后是核心的obtainFreshBeanFactory()方法统捶,這個方法是初始化BeanFactory榆芦,是整個refresh()方法的核心,其中完成了配置文件的加載喘鸟、解析匆绣、注冊,后面會專門詳細說 什黑。

這里要說明一下崎淳,ApplicationContext實現(xiàn)了BeanFactory接口,并實現(xiàn)了ResourceLoader愕把、MessageSource等接口拣凹,可以認為是增強的BeanFactory森爽。但是ApplicationContext并不自己重復實現(xiàn)BeanFactory定義的方法,而是委托給DefaultListableBeanFactory來實現(xiàn)嚣镜。這種設計思路也是值得學習的爬迟。
后面的 prepareBeanFactory()、postProcessBeanFactory()菊匿、invokeBeanFactoryPostProcessors()付呕、registerBeanPostProcessors()、initMessageSource()跌捆、initApplicationEventMulticaster()徽职、onRefresh()、registerListeners()佩厚、finishBeanFactoryInitialization()姆钉、finishRefresh()等方法,是添加一些后處理器抄瓦、廣播育韩、攔截器等,就不一個個細說了

其中的關鍵方法是finishBeanFactoryInitialization()闺鲸,在這個方法中,會對剛才注冊的Bean(不延遲加載的)埃叭,進行實例化摸恍,所以也是一個核心方法。

bean.xml的處理


從整體上介紹完了流程赤屋,接下來就重點看obtainFreshBeanFactory()方法立镶,上文說到,在這個方法里类早,完成了配置文件的加載媚媒、解析、注冊

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

這個方法做了2件事涩僻,首先通過refreshBeanFactory()方法缭召,創(chuàng)建了DefaultListableBeanFactory的實例,并進行初始化逆日。

protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

首先如果已經有BeanFactory實例嵌巷,就先清空。然后通過createBeanFactory()方法室抽,創(chuàng)建一個DefaultListableBeanFactory的實例

protected DefaultListableBeanFactory createBeanFactory() {
        return new DefaultListableBeanFactory(getInternalParentBeanFactory());
    }

接下來設置ID唯一標識

beanFactory.setSerializationId(getId());

然后允許用戶進行一些自定義的配置

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
        if (this.allowBeanDefinitionOverriding != null) {
            beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.allowCircularReferences != null) {
            beanFactory.setAllowCircularReferences(this.allowCircularReferences);
        }
        beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
    }

最后搪哪,就是核心的loadBeanDefinitions()方法

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }

這里首先會創(chuàng)建一個XmlBeanDefinitionReader的實例,然后進行初始化坪圾。這個XmlBeanDefinitionReader中其實傳遞的BeanDefinitionRegistry類型的實例晓折,為什么可以傳遞一個beanFactory呢惑朦,因為DefaultListableBeanFactory實現(xiàn)了BeanDefinitionRegistry接口,這里是多態(tài)的使用漓概。

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
}

這里要說明一下漾月,ApplicationContext并不自己負責配置文件的加載、解析垛耳、注冊栅屏,而是將這些工作委托給XmlBeanDefinitionReader來做。

loadBeanDefinitions(beanDefinitionReader);

這行代碼堂鲜,就是Bean定義讀取實際發(fā)生的地方栈雳。這里的工作,主要是XmlBeanDefinitionReader來完成的缔莲,下一篇博客會詳細介紹這個過程哥纫。

loadBeanDefinitions

loadBeanDefinitions: 源碼閱讀


入口是loadBeanDefinitions方法

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

這是解析過程最外圍的代碼,首先要獲取到配置文件的路徑痴奏,這在之前已經完成了蛀骇。
然后將每個配置文件的路徑,作為參數(shù)傳給BeanDefinitionReader的loadBeanDefinitions方法里

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

這個方法又調用了重載方法

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()的實現(xiàn)的前提條件是因為XmlBeanDefinitionReader在實例化的時候已經確定了創(chuàng)建了實例ResourceLoader實例, 代碼位于 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(); 
      }
}

這個方法比較長读拆,BeanDefinitionReader不能直接加載配置文件擅憔,需要把配置文件封裝成Resource,然后才能調用重載方法loadBeanDefinitions()檐晕。所以這個方法其實就是2段暑诸,第一部分是委托ResourceLoader將配置文件封裝成Resource,第二部分是調用loadBeanDefinitions()辟灰,對Resource進行解析

而這里的ResourceLoader个榕,就是前面的XmlWebApplicationContext,因為ApplicationContext接口芥喇,是繼承自ResourceLoader接口的

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

接下來進入重載方法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;
    }

這里就不用說了继控,就是把每一個Resource作為參數(shù)械馆,繼續(xù)調用重載方法。讀spring源碼湿诊,會發(fā)現(xiàn)重載方法特別多狱杰。

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

還是重載方法,不過這里對傳進來的Resource又進行了一次封裝厅须,變成了編碼后的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();
            }
        }
    }

這個就是loadBeanDefinitions()的最后一個重載方法,比較長,可以拆看來看错沽。

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

這第一部分簿晓,是處理線程相關的工作,把當前正在解析的Resource千埃,設置為當前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谒臼,然后調用實際解析的方法doLoadBeanDefinitions()。可以看到耀里,這種命名方式是很值得學習的蜈缤,一種業(yè)務方法,比如parse()冯挎,可能需要做一些外圍的工作底哥,然后實際解析的方法,可以命名為doParse()房官。這種doXXX()的命名方法趾徽,在很多開源框架中都有應用,比如logback等翰守。
接下來就看一下這個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讀取成標準的Document對象孵奶,然后調用registerBeanDefinitions(),進行解析工作蜡峰。

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

接下來就看一下這個核心方法registerBeanDefinitions

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

這里注意兩點 :

1.Document對象
首先這個Document對象事示,是W3C定義的標準XML對象,跟spring無關僻肖。其次這個registerBeanDefinitions方法肖爵,我覺得命名有點誤導性。因為這個時候實際上解析還沒有開始臀脏,怎么直接就注冊了呢劝堪。比較好的命名,我覺得可以是parseAndRegisterBeanDefinitions()揉稚。
2.documentReader的創(chuàng)建時使用反射創(chuàng)建的秒啦,代碼如下

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

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

private Class<?> documentReaderClass = 
DefaultBeanDefinitionDocumentReader.class;

所以創(chuàng)建的documentReaderClass是DefaultBeanDefinitionDocumentReader類的實例搀玖。
接下來就進入BeanDefinitionDocumentReader 中定義的registerBeanDefinitions()方法看看

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

處理完外圍事務之后余境,進入doRegisterBeanDefinitions()方法,這種命名規(guī)范,上文已經介紹過了

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

這個方法也比較長芳来,拆開來看

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屬性,就會進入這一段即舌,不過一般都是不會的

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

然后這里創(chuàng)建了BeanDefinitionParserDelegate對象佣盒,preProcessXml()和postProcessXml()都是空方法,核心就是parseBeanDefinitions()方法顽聂。這里又把BeanDefinition解析和注冊的工作肥惭,委托給了BeanDefinitionParserDelegate對象,在parseBeanDefinitions()方法中完成
總的來說紊搪,解析工作的委托鏈是這樣的:ClassPathXmlApplicationContext蜜葱,XmlBeanDefinitionReader,DefaultBeanDefinitionDocumentReader嗦明,BeanDefinitionParserDelegate
ClassPathXmlApplicationContext作為最外圍的組件笼沥,發(fā)起解析的請求
XmlBeanDefinitionReader將配置文件路徑封裝為Resource,讀取出w3c定義的Document對象娶牌,然后委托給DefaultBeanDefinitionDocumentReader
DefaultBeanDefinitionDocumentReader就開始做實際的解析工作了奔浅,但是涉及到bean的具體解析,它還是會繼續(xù)委托給BeanDefinitionParserDelegate來做诗良。
接下來在parseBeanDefinitions()方法中發(fā)生了什么汹桦,以及BeanDefinitionParserDelegate類完成的工作,在下一篇博客中繼續(xù)介紹鉴裹。

loadBeanDefinitions

BeanDefinition的解析,已經走到了DefaultBeanDefinitionDocumentR
eader里舞骆,這時候配置文件已經被加載,并解析成w3c的Document對象径荔。這篇博客就接著介紹督禽,DefaultBeanDefinitionDocumentReader和BeanDefinitionParserDelegate類,是怎么協(xié)同完成bean的解析和注冊的总处。

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

這段代碼狈惫,創(chuàng)建了一個BeanDefinitionParserDelegate組件,然后就是preProcessXml()鹦马、parseBeanDefinitions()胧谈、postProcessXml()方法
其中preProcessXml()和postProcessXml()默認是空方法,接下來就看下parseBeanDefinitions()方法

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
        if (delegate.isDefaultNamespace(root)) {
            NodeList nl = root.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                if (node instanceof Element) {
                    Element ele = (Element) node;
                    if (delegate.isDefaultNamespace(ele)) {
                        parseDefaultElement(ele, delegate);
                    }
                    else {
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        }
        else {
            delegate.parseCustomElement(root);
        }
    }

從這個方法開始荸频,BeanDefinitionParserDelegate就開始發(fā)揮作用了菱肖,判斷當前解析元素是否屬于默認的命名空間,如果是的話旭从,就調用parseDefaultElement()方法稳强,否則調用delegate上parseCustomElement()方法

public boolean isDefaultNamespace(String namespaceUri) {
        return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri));
    }
    public boolean isDefaultNamespace(Node node) {
        return isDefaultNamespace(getNamespaceURI(node));
    }

只有http://www.springframework.org/schema/beans场仲,會被認為是默認的命名空間。也就是說键袱,beans燎窘、bean這些元素,會認為屬于默認的命名空間蹄咖,而像task:scheduled這些褐健,就認為不屬于默認命名空間。
根節(jié)點beans的一個子節(jié)點bean澜汤,是屬于默認命名空間的蚜迅,所以會進入parseDefaultElement()方法

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
            importBeanDefinitionResource(ele);
        }
        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
            processAliasRegistration(ele);
        }
        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
            processBeanDefinition(ele, delegate);
        }
        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
            // recurse
            doRegisterBeanDefinitions(ele);
        }
    }

這里可能會有4種情況,import俊抵、alias谁不、bean、beans徽诲,分別有一個方法與之對應刹帕,這里解析的是bean元素,所以會進入processBeanDefinition()方法

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                // Register the final decorated instance.
                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
            }
            catch (BeanDefinitionStoreException ex) {
                getReaderContext().error("Failed to register bean definition with name '" +
                        bdHolder.getBeanName() + "'", ele, ex);
            }
            // Send registration event.
            getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
        }
    }

這里主要有3個步驟谎替,先是委托delegate對bean進行解析偷溺,然后委托delegate對bean進行裝飾,最后由一個工具類來完成BeanDefinition的注冊
可以看出來钱贯,DefaultBeanDefinitionDocumentReader不負責任何具體的bean解析挫掏,它面向的是xml Document對象,根據(jù)其元素的命名空間和名稱秩命,起一個類似路由的作用(不過尉共,命名空間的判斷,也是委托給delegate來做的)弃锐。所以這個類的命名袄友,是比較貼切的,突出了其面向Document的特性霹菊。具體的工作杠河,是由BeanDefinitionParserDelegate來完成的
下面就看下parseBeanDefinitionElement()方法

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
        String id = ele.getAttribute(ID_ATTRIBUTE);
        String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
        List<String> aliases = new ArrayList<String>();
        if (StringUtils.hasLength(nameAttr)) {
            String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            aliases.addAll(Arrays.asList(nameArr));
        }
        String beanName = id;
        if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
            beanName = aliases.remove(0);
            if (logger.isDebugEnabled()) {
                logger.debug("No XML 'id' specified - using '" + beanName +
                        "' as bean name and " + aliases + " as aliases");
            }
        }
        if (containingBean == null) {
            checkNameUniqueness(beanName, aliases, ele);
        }
        AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
        if (beanDefinition != null) {
            if (!StringUtils.hasText(beanName)) {
                try {
                    if (containingBean != null) {
                        beanName = BeanDefinitionReaderUtils.generateBeanName(
                                beanDefinition, this.readerContext.getRegistry(), true);
                    }
                    else {
                        beanName = this.readerContext.generateBeanName(beanDefinition);
                        // Register an alias for the plain bean class name, if still possible,
                        // if the generator returned the class name plus a suffix.
                        // This is expected for Spring 1.2/2.0 backwards compatibility.
                        String beanClassName = beanDefinition.getBeanClassName();
                        if (beanClassName != null &&
                                beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&                      !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
                            aliases.add(beanClassName);
                        }
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("Neither XML 'id' nor 'name' specified - " +
                                "using generated bean name [" + beanName + "]");
                    }
                }
                catch (Exception ex) {
                    error(ex.getMessage(), ele);
                    return null;
                }
            }
            String[] aliasesArray = StringUtils.toStringArray(aliases);
            return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
        }
        return null;
    }

這個方法很長,可以分成三段來看

String id = ele.getAttribute(ID_ATTRIBUTE);
        String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
        List<String> aliases = new ArrayList<String>();
        if (StringUtils.hasLength(nameAttr)) {
            String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            aliases.addAll(Arrays.asList(nameArr));
        }
        String beanName = id;
        if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
            beanName = aliases.remove(0);
            if (logger.isDebugEnabled()) {
                logger.debug("No XML 'id' specified - using '" + beanName +
                        "' as bean name and " + aliases + " as aliases");
            }
        }
        if (containingBean == null) {
            checkNameUniqueness(beanName, aliases, ele);
        }

這一段浇辜,主要是處理一些跟alias,id等標識相關的東西

AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);

這一行是核心唾戚,進行實際的解析

if (beanDefinition != null) {
            if (!StringUtils.hasText(beanName)) {
                try {
                    if (containingBean != null) {
                        beanName = BeanDefinitionReaderUtils.generateBeanName(
                                beanDefinition, this.readerContext.getRegistry(), true);
                    }
                    else {
                        beanName = this.readerContext.generateBeanName(beanDefinition);
                        // Register an alias for the plain bean class name, if still possible,
                        // if the generator returned the class name plus a suffix.
                        // This is expected for Spring 1.2/2.0 backwards compatibility.
                        String beanClassName = beanDefinition.getBeanClassName();
                        if (beanClassName != null &&
                                beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
                                !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
                            aliases.add(beanClassName);
                        }
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("Neither XML 'id' nor 'name' specified - " +
                                "using generated bean name [" + beanName + "]");
                    }
                }
                catch (Exception ex) {
                    error(ex.getMessage(), ele);
                    return null;
                }
            }
            String[] aliasesArray = StringUtils.toStringArray(aliases);
            return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
        }

這段是后置處理柳洋,對beanName進行處理
前置處理和后置處理,不是核心叹坦,就不細看了熊镣,重點看下核心的那一行調用

public AbstractBeanDefinition parseBeanDefinitionElement(
            Element ele, String beanName, BeanDefinition containingBean) {
        this.parseState.push(new BeanEntry(beanName));
        String className = null;
        if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
            className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
        }
        try {
            String parent = null;
            if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
                parent = ele.getAttribute(PARENT_ATTRIBUTE);
            }
            AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
            bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            parseMetaElements(ele, bd);
            parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
            parseReplacedMethodSubElements(ele,   bd.getMethodOverrides());
            parseConstructorArgElements(ele, bd);
            parsePropertyElements(ele, bd);
            parseQualifierElements(ele, bd);
            bd.setResource(this.readerContext.getResource());
            bd.setSource(extractSource(ele));
            return bd;
        }
        catch (ClassNotFoundException ex) {
            error("Bean class [" + className + "] not found", ele, ex);
        }
        catch (NoClassDefFoundError err) {
            error("Class that bean class [" + className + "] depends on not found", ele, err);
        }
        catch (Throwable ex) {
            error("Unexpected failure during bean definition parsing", ele, ex);
        }
        finally {
            this.parseState.pop();
        }
        return null;
    }

這個方法也挺長的,拆開看看

this.parseState.push(new BeanEntry(beanName));
        String className = null;
        if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
            className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
        }

這段是從配置中抽取出類名。接下來的長長一段绪囱,把異常處理先拋開测蹲,看看實際的業(yè)務

            String parent = null;
            if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
                parent = ele.getAttribute(PARENT_ATTRIBUTE);
            }
            AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);                  
            bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            parseMetaElements(ele, bd);
            parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
            parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
            parseConstructorArgElements(ele, bd);
            parsePropertyElements(ele, bd);
            parseQualifierElements(ele, bd);
            bd.setResource(this.readerContext.getResource());
            bd.setSource(extractSource(ele));
            return bd;

這里每個方法的命名,就說明了是要干什么鬼吵,可以一個個跟進去看扣甲,本文就不細說了〕菀危總之琉挖,經過這里的解析,就得到了一個完整的BeanDefinitionHolder涣脚。只是說明一下示辈,如果在配置文件里,沒有對一些屬性進行設置遣蚀,比如autowire-candidate等矾麻,那么這個解析生成的BeanDefinition,都會得到一個默認值
然后芭梯,對這個Bean做一些必要的裝飾

public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
            Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {
        BeanDefinitionHolder finalDefinition = definitionHolder;
        // Decorate based on custom attributes first.
        NamedNodeMap attributes = ele.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node node = attributes.item(i);
            finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
        }
        // Decorate based on custom nested elements.
        NodeList children = ele.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
            }
        }
        return finalDefinition;
    }

持續(xù)單步調試险耀,代碼繼續(xù)運行到DefaultBeanDefinitionDocumentReader中的processBeanDefinition中的registerBeanDefinition()

BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, 
getReaderContext().getRegistry());

單步進入代碼發(fā)現(xiàn)BeanDefinitionReaderUtils靜態(tài)方法registerBeanDefinition()

public static void registerBeanDefinition(
            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
            throws BeanDefinitionStoreException {
        // Register bean definition under primary name.
        String beanName = definitionHolder.getBeanName();
        // 其實調用的是DefaultListableBeanFactory中的registerBeanDefinition方法
        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
        // Register aliases for bean name, if any.
        String[] aliases = definitionHolder.getAliases();
        if (aliases != null) {
            for (String aliase : aliases) {
                registry.registerAlias(beanName, aliase);
            }
        }
    }

解釋一下其實調用的是DefaultListableBeanFactory中的registerBeanDefinition方法這句話,因為DefaultListableBeanFactory實現(xiàn)BeanDefinitionRegistry接口粥帚,BeanDefinitionRegistry接口中定義了registerBeanDefinition()方法
看下DefaultListableBeanFactory中registerBeanDefinition()實例方法的具體實現(xiàn):

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException {
        Assert.hasText(beanName, "Bean name must not be empty");
        Assert.notNull(beanDefinition, "BeanDefinition must not be null");
        if (beanDefinition instanceof AbstractBeanDefinition) {
            try {
                ((AbstractBeanDefinition) beanDefinition).validate();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Validation of bean definition failed", ex);
            }
        }
        synchronized (this.beanDefinitionMap) {
            Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
            if (oldBeanDefinition != null) {
                if (!this.allowBeanDefinitionOverriding) {
                    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                            "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                            "': There is already [" + oldBeanDefinition + "] bound.");
                }
                else {
                    if (this.logger.isInfoEnabled()) {
                        this.logger.info("Overriding bean definition for bean '" + beanName +
                                "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
                    }
                }
            }
            else {
                this.beanDefinitionNames.add(beanName);
                this.frozenBeanDefinitionNames = null;
            }
            this.beanDefinitionMap.put(beanName, beanDefinition);
            resetBeanDefinition(beanName);
        }
    }

代碼追溯之后發(fā)現(xiàn)這個方法里胰耗,最關鍵的是以下2行:

this.beanDefinitionNames.add(beanName);
this.beanDefinitionMap.put(beanName, beanDefinition);

前者是把beanName放到隊列里,后者是把BeanDefinition放到map中芒涡,到此注冊就完成了柴灯。在后面實例化的時候,就是把beanDefinitionMap中的BeanDefinition取出來费尽,逐一實例化
BeanFactory準備完畢之后赠群,代碼又回到了ClassPathXmlApplicationContext里

public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();
            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);
            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);
                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);
                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);
                // Initialize message source for this context.
                initMessageSource();
                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();
                // Initialize other special beans in specific context subclasses.
                onRefresh();
                // Check for listener beans and register them.
                registerListeners();
                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);
                // Last step: publish corresponding event.
                finishRefresh();
            }
            catch (BeansException ex) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();
                // Reset 'active' flag.
                cancelRefresh(ex);
                // Propagate exception to caller.
                throw ex;
            }
        }
    }

也就是obtainFreshBeanFactory()方法執(zhí)行之后,再進行下面的步驟旱幼。
總結來說查描,ApplicationContext將解析配置文件的工作委托給BeanDefinitionReader,然后BeanDefinitionReader將配置文件讀取為xml的Document文檔之后柏卤,又委托給BeanDefinitionDocumentReader
BeanDefinitionDocumentReader這個組件是根據(jù)xml元素的命名空間和元素名冬三,起到一個路由的作用,實際的解析工作缘缚,是委托給BeanDefinitionParserDelegate來完成的勾笆。

BeanDefinitionParserDelegate的解析工作完成以后,會返回BeanDefinitionHolder給BeanDefinitionDocumentReader桥滨,在這里窝爪,會委托給DefaultListableBeanFactory完成bean的注冊
XmlBeanDefinitionReader(計數(shù)弛车、解析XML文檔),BeanDefinitionDocumentReader(依賴xml文檔蒲每,進行解析和注冊)纷跛,BeanDefinitionParserDelegate(實際的解析工作)。

可以看出邀杏,在解析bean的過程中贫奠,這3個組件的分工是比較清晰的,各司其職淮阐,這種設計思想值得學習
到此為止叮阅,bean的解析、注冊泣特、spring ioc 容器的實例化過程就基本分析結束了浩姥。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市状您,隨后出現(xiàn)的幾起案子勒叠,更是在濱河造成了極大的恐慌,老刑警劉巖膏孟,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件眯分,死亡現(xiàn)場離奇詭異,居然都是意外死亡柒桑,警方通過查閱死者的電腦和手機弊决,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來魁淳,“玉大人飘诗,你說我怎么就攤上這事〗绻洌” “怎么了昆稿?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長息拜。 經常有香客問我溉潭,道長专挪,這世上最難降的妖魔是什么积瞒? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任或听,我火速辦了婚禮买猖,結果婚禮上,老公的妹妹穿的比我還像新娘瞬测。我一直安慰自己劣欢,他們只是感情好杉畜,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布氯庆。 她就那樣靜靜地躺著蹭秋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪堤撵。 梳的紋絲不亂的頭發(fā)上仁讨,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機與錄音实昨,去河邊找鬼洞豁。 笑死,一個胖子當著我的面吹牛荒给,可吹牛的內容都是我干的丈挟。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼志电,長吁一口氣:“原來是場噩夢啊……” “哼曙咽!你這毒婦竟也來了?” 一聲冷哼從身側響起挑辆,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤例朱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后鱼蝉,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體洒嗤,經...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年魁亦,在試婚紗的時候發(fā)現(xiàn)自己被綠了渔隶。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡洁奈,死狀恐怖间唉,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情睬魂,我是刑警寧澤终吼,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站氯哮,受9級特大地震影響际跪,放射性物質發(fā)生泄漏。R本人自食惡果不足惜喉钢,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一姆打、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧肠虽,春花似錦幔戏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽痊剖。三九已至,卻和暖如春垒玲,著一層夾襖步出監(jiān)牢的瞬間陆馁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工合愈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留叮贩,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓佛析,卻偏偏與公主長得像益老,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子寸莫,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內容