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

  • 2019 年 11 月 26 日
  • 筆記

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

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/beanshttp://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 DefaultListableBeanFactoryextends AbstractAutowireCapableBeanFactory   implementsConfigurableListableBeanFactory, 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 容器的實例化過程就基本分析結束了。