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

spring ioc 容器的加載流程

1.目標:熟練使用spring,並分析其源碼,瞭解其中的思想。這篇主要介紹spring ioc 容器的加載java

2.前提條件:會使用debugnode

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

4.注意:因爲Spring的類繼承體系比較複雜,不能所有貼圖,因此只將分析源碼以後發現的最主要的類繼承結構類圖貼在下方。web

**5.關於Spring Ioc
Demo:**咱們從demo入手一步步進行代碼追溯。面試

Spring Ioc Demo

    • *
1.定義數據訪問接口IUserDao.java
public interface IUserDao {  
    public void InsertUser(String username,String password);
}

2.定義IUserDao.java實現類IUserDaoImpl.javaspring

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

3.定義業務邏輯接口UserService.java數據庫

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

4.定義UserService.java實現類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實現類繼承AbstractXmlApplication 抽象類
3.AbstractXmlApplication 繼承AbstractRefreshableConfigApplicationContext
4.AbstractRefreshableConfigApplicationContext抽象類繼承AbstractRefreshableApplicationContext
5.AbstractRefreshableApplicationContext 繼承 AbstractApplicationContext
6.AbstractApplicationContext 實現ConfigurableApplicationContext 接口
7.ConfigurableApplicationContext 接口繼承
ApplicationContext接口
整體來講繼承實現結構較深,內部使用了大量適配器模式。
以ClassPathXmlApplicationContext爲例,繼承類圖以下圖所示:

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

    • *

在開始以前,先介紹一個總體的概念。即spring ioc容器的加載,大致上通過如下幾個過程:
資源文件定位、解析、註冊、實例化架構

1.資源文件定位
其中資源文件定位,通常是在ApplicationContext的實現類裏完成的,由於ApplicationContext接口繼承ResourcePatternResolver 接口,ResourcePatternResolver接口繼承ResourceLoader接口,ResourceLoader其中的getResource()方法,能夠將外部的資源,讀取爲Resource類。
    • *

2.解析DefaultBeanDefinitionDocumentReader,
解析主要是在BeanDefinitionReader中完成的,最經常使用的實現類是XmlBeanDefinitionReader,其中的loadBeanDefinitions()方法,負責讀取Resource,並完成後續的步驟。ApplicationContext完成資源文件定位以後,是將解析工做委託給XmlBeanDefinitionReader來完成的
解析這裏涉及到不少步驟,最多見的狀況,資源文件來自一個XML配置文件。首先是BeanDefinitionReader,將XML文件讀取成w3c的Document文檔。
DefaultBeanDefinitionDocumentReader對Document進行進一步解析。而後DefaultBeanDefinitionDocumentReader又委託給BeanDefinitionParserDelegate進行解析。若是是標準的xml namespace元素,會在Delegate內部完成解析,若是是非標準的xml namespace元素,則會委託合適的NamespaceHandler進行解析最終解析的結果都封裝爲BeanDefinitionHolder,至此解析就算完成。
後續會進行細緻講解。

    • *

3.註冊
而後bean的註冊是在BeanFactory裏完成的,BeanFactory接口最多見的一個實現類是DefaultListableBeanFactory,它實現了BeanDefinitionRegistry接口,因此其中的registerBeanDefinition()方法,能夠對BeanDefinition進行註冊這裏附帶一提,最多見的XmlWebApplicationContext不是本身持有BeanDefinition的,它繼承自AbstractRefreshableApplicationContext,其持有一個DefaultListableBeanFactory的字段,就是用它來保存BeanDefinition
所謂的註冊,其實就是將BeanDefinition的name和實例,保存到一個Map中。剛纔說到,最經常使用的實現DefaultListableBeanFactory,其中的字段就是beanDefinitionMap,是一個ConcurrentHashMap。
代碼以下:
>1.DefaultListableBeanFactory繼承實現關係

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); 
     //實現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 追溯源碼的過程,大概分三個篇幅,這是第一篇,現總體瞭解一下運行流程,定位資源加載,資源解析,bean 註冊發生的位置。
2. 記錄結構:
1.調試棧截圖
2.總體流程
3.bean.xml的處理
每段代碼下面有相應的講解

調試棧截圖

    • *

每一個棧幀中方法的行號都有標明,按照行號追溯源碼,而後配合教程可以快速學習。

總體流程

    • *

ioc容器實例化代碼

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

進入代碼中一步步追溯,發現重要方法: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實現了BeanFactory接口,並實現了ResourceLoader、MessageSource等接口,能夠認爲是加強的BeanFactory。可是ApplicationContext並不本身重複實現BeanFactory定義的方法,而是委託給DefaultListableBeanFactory來實現。這種設計思路也是值得學習的。
後面的 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()方法,建立了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()方法,建立一個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);
    }

這裏首先會建立一個XmlBeanDefinitionReader的實例,而後進行初始化。這個XmlBeanDefinitionReader中其實傳遞的BeanDefinitionRegistry類型的實例,爲何能夠傳遞一個beanFactory呢,由於DefaultListableBeanFactory實現了BeanDefinitionRegistry接口,這裏是多態的使用。

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定義讀取實際發生的地方。這裏的工做,主要是XmlBeanDefinitionReader來完成的,下一篇博客會詳細介紹這個過程。

loadBeanDefinitions

loadBeanDefinitions: 源碼閱讀

    • *

入口是loadBeanDefinitions方法

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

這是解析過程最外圍的代碼,首先要獲取到配置文件的路徑,這在以前已經完成了。
而後將每一個配置文件的路徑,做爲參數傳給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()的實現的前提條件是由於XmlBeanDefinitionReader在實例化的時候已經肯定了建立了實例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環境下,這裏就是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做爲參數,繼續調用重載方法。讀spring源碼,會發現重載方法特別多。

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()。能夠看到,這種命名方式是很值得學習的,一種業務方法,好比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 {
        //建立的實際上是DefaultBeanDefinitionDocumentReader 的實例,利用反射建立的。
        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的建立時使用反射建立的,代碼以下
protected BeanDefinitionDocumentReader    
 createBeanDefinitionDocumentReader() {   
          return BeanDefinitionDocumentReader.class.cast(BeanUtils.
            instantiateClass(this.documentReaderClass));
}

instantiateClass方法中傳入了一個Class類型的參數。追溯發現下述代碼:

private Class<?> documentReaderClass = 
DefaultBeanDefinitionDocumentReader.class;

因此建立的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()方法,這種命名規範,上文已經介紹過了

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;

而後這裏建立了BeanDefinitionParserDelegate對象,preProcessXml()和postProcessXml()都是空方法,核心就是parseBeanDefinitions()方法。這裏又把BeanDefinition解析和註冊的工做,委託給了BeanDefinitionParserDelegate對象,在parseBeanDefinitions()方法中完成
總的來講,解析工做的委託鏈是這樣的:ClassPathXmlApplicationContext,XmlBeanDefinitionReader,DefaultBeanDefinitionDocumentReader,BeanDefinitionParserDelegate
ClassPathXmlApplicationContext做爲最外圍的組件,發起解析的請求
XmlBeanDefinitionReader將配置文件路徑封裝爲Resource,讀取出w3c定義的Document對象,而後委託給DefaultBeanDefinitionDocumentReader
DefaultBeanDefinitionDocumentReader就開始作實際的解析工做了,可是涉及到bean的具體解析,它仍是會繼續委託給BeanDefinitionParserDelegate來作。
接下來在parseBeanDefinitions()方法中發生了什麼,以及BeanDefinitionParserDelegate類完成的工做,在下一篇博客中繼續介紹。

loadBeanDefinitions

BeanDefinition的解析,已經走到了DefaultBeanDefinitionDocumentR
eader裏,這時候配置文件已經被加載,並解析成w3c的Document對象。這篇博客就接着介紹,DefaultBeanDefinitionDocumentReader和BeanDefinitionParserDelegate類,是怎麼協同完成bean的解析和註冊的。
BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createHelper(readerContext, root, parent);
        preProcessXml(root);
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);
        this.delegate = parent;

這段代碼,建立了一個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就開始發揮做用了,判斷當前解析元素是否屬於默認的命名空間,若是是的話,就調用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這些,就認爲不屬於默認命名空間。
根節點beans的一個子節點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對象,根據其元素的命名空間和名稱,起一個相似路由的做用(不過,命名空間的判斷,也是委託給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();
        }

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

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

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

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

單步進入代碼發現BeanDefinitionReaderUtils靜態方法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實現BeanDefinitionRegistry接口,BeanDefinitionRegistry接口中定義了registerBeanDefinition()方法
看下DefaultListableBeanFactory中registerBeanDefinition()實例方法的具體實現:

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

代碼追溯以後發現這個方法裏,最關鍵的是如下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()方法執行以後,再進行下面的步驟。
總結來講,ApplicationContext將解析配置文件的工做委託給BeanDefinitionReader,而後BeanDefinitionReader將配置文件讀取爲xml的Document文檔以後,又委託給BeanDefinitionDocumentReader
BeanDefinitionDocumentReader這個組件是根據xml元素的命名空間和元素名,起到一個路由的做用,實際的解析工做,是委託給BeanDefinitionParserDelegate來完成的
BeanDefinitionParserDelegate的解析工做完成之後,會返回BeanDefinitionHolder給BeanDefinitionDocumentReader,在這裏,會委託給DefaultListableBeanFactory完成bean的註冊
XmlBeanDefinitionReader(計數、解析XML文檔),BeanDefinitionDocumentReader(依賴xml文檔,進行解析和註冊),BeanDefinitionParserDelegate(實際的解析工做)。能夠看出,在解析bean的過程當中,這3個組件的分工是比較清晰的,各司其職,這種設計思想值得學習
到此爲止,bean的解析、註冊、spring ioc 容器的實例化過程就基本分析結束了。

spring ioc 容器的加載流程

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

2.前提條件:會使用debug

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

4.注意:因爲Spring的類繼承體系比較複雜,不能所有貼圖,因此只將分析源碼以後發現的最主要的類繼承結構類圖貼在下方。

**5.關於Spring Ioc
Demo:**咱們從demo入手一步步進行代碼追溯。

Spring Ioc Demo

    • *
1.定義數據訪問接口IUserDao.java
public interface IUserDao {  
    public void InsertUser(String username,String password);
}

2.定義IUserDao.java實現類IUserDaoImpl.java

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

3.定義業務邏輯接口UserService.java

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

4.定義UserService.java實現類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實現類繼承AbstractXmlApplication 抽象類
3.AbstractXmlApplication 繼承AbstractRefreshableConfigApplicationContext
4.AbstractRefreshableConfigApplicationContext抽象類繼承AbstractRefreshableApplicationContext
5.AbstractRefreshableApplicationContext 繼承 AbstractApplicationContext
6.AbstractApplicationContext 實現ConfigurableApplicationContext 接口
7.ConfigurableApplicationContext 接口繼承
ApplicationContext接口
整體來講繼承實現結構較深,內部使用了大量適配器模式。
以ClassPathXmlApplicationContext爲例,繼承類圖以下圖所示:

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

    • *

在開始以前,先介紹一個總體的概念。即spring ioc容器的加載,大致上通過如下幾個過程:
資源文件定位、解析、註冊、實例化

1.資源文件定位
其中資源文件定位,通常是在ApplicationContext的實現類裏完成的,由於ApplicationContext接口繼承ResourcePatternResolver 接口,ResourcePatternResolver接口繼承ResourceLoader接口,ResourceLoader其中的getResource()方法,能夠將外部的資源,讀取爲Resource類。
    • *

2.解析DefaultBeanDefinitionDocumentReader,
解析主要是在BeanDefinitionReader中完成的,最經常使用的實現類是XmlBeanDefinitionReader,其中的loadBeanDefinitions()方法,負責讀取Resource,並完成後續的步驟。ApplicationContext完成資源文件定位以後,是將解析工做委託給XmlBeanDefinitionReader來完成的
解析這裏涉及到不少步驟,最多見的狀況,資源文件來自一個XML配置文件。首先是BeanDefinitionReader,將XML文件讀取成w3c的Document文檔。
DefaultBeanDefinitionDocumentReader對Document進行進一步解析。而後DefaultBeanDefinitionDocumentReader又委託給BeanDefinitionParserDelegate進行解析。若是是標準的xml namespace元素,會在Delegate內部完成解析,若是是非標準的xml namespace元素,則會委託合適的NamespaceHandler進行解析最終解析的結果都封裝爲BeanDefinitionHolder,至此解析就算完成。
後續會進行細緻講解。

    • *

3.註冊
而後bean的註冊是在BeanFactory裏完成的,BeanFactory接口最多見的一個實現類是DefaultListableBeanFactory,它實現了BeanDefinitionRegistry接口,因此其中的registerBeanDefinition()方法,能夠對BeanDefinition進行註冊這裏附帶一提,最多見的XmlWebApplicationContext不是本身持有BeanDefinition的,它繼承自AbstractRefreshableApplicationContext,其持有一個DefaultListableBeanFactory的字段,就是用它來保存BeanDefinition
所謂的註冊,其實就是將BeanDefinition的name和實例,保存到一個Map中。剛纔說到,最經常使用的實現DefaultListableBeanFactory,其中的字段就是beanDefinitionMap,是一個ConcurrentHashMap。
代碼以下:
>1.DefaultListableBeanFactory繼承實現關係

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); 
     //實現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 追溯源碼的過程,大概分三個篇幅,這是第一篇,現總體瞭解一下運行流程,定位資源加載,資源解析,bean 註冊發生的位置。
2. 記錄結構:
1.調試棧截圖
2.總體流程
3.bean.xml的處理
每段代碼下面有相應的講解

調試棧截圖

    • *

每一個棧幀中方法的行號都有標明,按照行號追溯源碼,而後配合教程可以快速學習。

總體流程

    • *

ioc容器實例化代碼

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

進入代碼中一步步追溯,發現重要方法: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實現了BeanFactory接口,並實現了ResourceLoader、MessageSource等接口,能夠認爲是加強的BeanFactory。可是ApplicationContext並不本身重複實現BeanFactory定義的方法,而是委託給DefaultListableBeanFactory來實現。這種設計思路也是值得學習的。
後面的 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()方法,建立了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()方法,建立一個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);
    }

這裏首先會建立一個XmlBeanDefinitionReader的實例,而後進行初始化。這個XmlBeanDefinitionReader中其實傳遞的BeanDefinitionRegistry類型的實例,爲何能夠傳遞一個beanFactory呢,由於DefaultListableBeanFactory實現了BeanDefinitionRegistry接口,這裏是多態的使用。

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定義讀取實際發生的地方。這裏的工做,主要是XmlBeanDefinitionReader來完成的,下一篇博客會詳細介紹這個過程。

loadBeanDefinitions

loadBeanDefinitions: 源碼閱讀

    • *

入口是loadBeanDefinitions方法

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

這是解析過程最外圍的代碼,首先要獲取到配置文件的路徑,這在以前已經完成了。
而後將每一個配置文件的路徑,做爲參數傳給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()的實現的前提條件是由於XmlBeanDefinitionReader在實例化的時候已經肯定了建立了實例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環境下,這裏就是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做爲參數,繼續調用重載方法。讀spring源碼,會發現重載方法特別多。

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()。能夠看到,這種命名方式是很值得學習的,一種業務方法,好比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 {
        //建立的實際上是DefaultBeanDefinitionDocumentReader 的實例,利用反射建立的。
        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的建立時使用反射建立的,代碼以下
protected BeanDefinitionDocumentReader    
 createBeanDefinitionDocumentReader() {   
          return BeanDefinitionDocumentReader.class.cast(BeanUtils.
            instantiateClass(this.documentReaderClass));
}

instantiateClass方法中傳入了一個Class類型的參數。追溯發現下述代碼:

private Class<?> documentReaderClass = 
DefaultBeanDefinitionDocumentReader.class;

因此建立的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()方法,這種命名規範,上文已經介紹過了

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;

而後這裏建立了BeanDefinitionParserDelegate對象,preProcessXml()和postProcessXml()都是空方法,核心就是parseBeanDefinitions()方法。這裏又把BeanDefinition解析和註冊的工做,委託給了BeanDefinitionParserDelegate對象,在parseBeanDefinitions()方法中完成
總的來講,解析工做的委託鏈是這樣的:ClassPathXmlApplicationContext,XmlBeanDefinitionReader,DefaultBeanDefinitionDocumentReader,BeanDefinitionParserDelegate
ClassPathXmlApplicationContext做爲最外圍的組件,發起解析的請求
XmlBeanDefinitionReader將配置文件路徑封裝爲Resource,讀取出w3c定義的Document對象,而後委託給DefaultBeanDefinitionDocumentReader
DefaultBeanDefinitionDocumentReader就開始作實際的解析工做了,可是涉及到bean的具體解析,它仍是會繼續委託給BeanDefinitionParserDelegate來作。
接下來在parseBeanDefinitions()方法中發生了什麼,以及BeanDefinitionParserDelegate類完成的工做,在下一篇博客中繼續介紹。

loadBeanDefinitions

BeanDefinition的解析,已經走到了DefaultBeanDefinitionDocumentR
eader裏,這時候配置文件已經被加載,並解析成w3c的Document對象。這篇博客就接着介紹,DefaultBeanDefinitionDocumentReader和BeanDefinitionParserDelegate類,是怎麼協同完成bean的解析和註冊的。
BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createHelper(readerContext, root, parent);
        preProcessXml(root);
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);
        this.delegate = parent;

這段代碼,建立了一個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就開始發揮做用了,判斷當前解析元素是否屬於默認的命名空間,若是是的話,就調用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這些,就認爲不屬於默認命名空間。
根節點beans的一個子節點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對象,根據其元素的命名空間和名稱,起一個相似路由的做用(不過,命名空間的判斷,也是委託給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();
        }

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

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

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

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

單步進入代碼發現BeanDefinitionReaderUtils靜態方法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實現BeanDefinitionRegistry接口,BeanDefinitionRegistry接口中定義了registerBeanDefinition()方法
看下DefaultListableBeanFactory中registerBeanDefinition()實例方法的具體實現:

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

代碼追溯以後發現這個方法裏,最關鍵的是如下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()方法執行以後,再進行下面的步驟。
總結來講,ApplicationContext將解析配置文件的工做委託給BeanDefinitionReader,而後BeanDefinitionReader將配置文件讀取爲xml的Document文檔以後,又委託給BeanDefinitionDocumentReader
BeanDefinitionDocumentReader這個組件是根據xml元素的命名空間和元素名,起到一個路由的做用,實際的解析工做,是委託給BeanDefinitionParserDelegate來完成的
BeanDefinitionParserDelegate的解析工做完成之後,會返回BeanDefinitionHolder給BeanDefinitionDocumentReader,在這裏,會委託給DefaultListableBeanFactory完成bean的註冊
XmlBeanDefinitionReader(計數、解析XML文檔),BeanDefinitionDocumentReader(依賴xml文檔,進行解析和註冊),BeanDefinitionParserDelegate(實際的解析工做)。能夠看出,在解析bean的過程當中,這3個組件的分工是比較清晰的,各司其職,這種設計思想值得學習
到此爲止,bean的解析、註冊、spring ioc 容器的實例化過程就基本分析結束了。

圖片描述

微信公衆號【黃小斜】做者是螞蟻金服 JAVA 工程師,專一於 JAVA 後端技術棧:SpringBoot、SSM全家桶、MySQL、分佈式、中間件、微服務,同時也懂點投資理財,堅持學習和寫做,相信終身學習的力量!關注公衆號後回覆」架構師「便可領取 Java基礎、進階、項目和架構師等免費學習資料,更有數據庫、分佈式、微服務等熱門技術學習視頻,內容豐富,兼顧原理和實踐,另外也將贈送做者原創的Java學習指南、Java程序員面試指南等乾貨資源
相關文章
相關標籤/搜索