Spring核心探索與總結(二):Spring容器初始化源碼探索

Spring容器概述

容器是spring的核心,Spring容器使用DI管理構成應用的組件,它會創建相互協作的組件之間的關聯,負責創建對象,裝配它們,配置它們並管理它們的生命週期,從生存到死亡(在這裏,可能就是new 到 finalize())。
Spring容器不只有一個。Spring自帶了多個容器實現,可以歸納爲兩種不同的類型:
1、bean工廠(由beanFactory接口定義)是最簡單的容器,提供基本的DI支持。
2、應用上下文(由ApplicationContext接口定義),基於BeanFactory構建,並且提供應用框架級別的服務。

ApplicationContext容器

相比bean工廠,ApplicationContext在實際的應用中顯得更受歡迎,下面着重介紹後者。
先來看下ApplicationContext的源碼。

package org.springframework.context;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * Central interface to provide configuration for an application.
 * This is read-only while the application is running, but may be
 * reloaded if the implementation supports this.
 *
 * <p>An ApplicationContext provides:
 * <ul>
 * <li>Bean factory methods for accessing application components.
 * Inherited from {@link org.springframework.beans.factory.ListableBeanFactory}.
 * <li>The ability to load file resources in a generic fashion.
 * Inherited from the {@link org.springframework.core.io.ResourceLoader} interface.
 * <li>The ability to publish events to registered listeners.
 * Inherited from the {@link ApplicationEventPublisher} interface.
 * <li>The ability to resolve messages, supporting internationalization.
 * Inherited from the {@link MessageSource} interface.
 * <li>Inheritance from a parent context. Definitions in a descendant context
 * will always take priority. This means, for example, that a single parent
 * context can be used by an entire web application, while each servlet has
 * its own child context that is independent of that of any other servlet.
 * </ul>
 *
 * <p>In addition to standard {@link org.springframework.beans.factory.BeanFactory}
 * lifecycle capabilities, ApplicationContext implementations detect and invoke
 * {@link ApplicationContextAware} beans as well as {@link ResourceLoaderAware},
 * {@link ApplicationEventPublisherAware} and {@link MessageSourceAware} beans.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see ConfigurableApplicationContext
 * @see org.springframework.beans.factory.BeanFactory
 * @see org.springframework.core.io.ResourceLoader
 */
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
        MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

    /**
     * Return the unique id of this application context.
     * @return the unique id of the context, or {@code null} if none
     */
    String getId();

    /**
     * Return a name for the deployed application that this context belongs to.
     * @return a name for the deployed application, or the empty String by default
     */
    String getApplicationName();

    /**
     * Return a friendly name for this context.
     * @return a display name for this context (never {@code null})
     */
    String getDisplayName();

    /**
     * Return the timestamp when this context was first loaded.
     * @return the timestamp (ms) when this context was first loaded
     */
    long getStartupDate();

    /**
     * Return the parent context, or {@code null} if there is no parent
     * and this is the root of the context hierarchy.
     * @return the parent context, or {@code null} if there is no parent
     */
    ApplicationContext getParent();

    /**
     * Expose AutowireCapableBeanFactory functionality for this context.
     * <p>This is not typically used by application code, except for the purpose of
     * initializing bean instances that live outside of the application context,
     * applying the Spring bean lifecycle (fully or partly) to them.
     * <p>Alternatively, the internal BeanFactory exposed by the
     * {@link ConfigurableApplicationContext} interface offers access to the
     * {@link AutowireCapableBeanFactory} interface too. The present method mainly
     * serves as a convenient, specific facility on the ApplicationContext interface.
     * <p><b>NOTE: As of 4.2, this method will consistently throw IllegalStateException
     * after the application context has been closed.</b> In current Spring Framework
     * versions, only refreshable application contexts behave that way; as of 4.2,
     * all application context implementations will be required to comply.
     * @return the AutowireCapableBeanFactory for this context
     * @throws IllegalStateException if the context does not support the
     * {@link AutowireCapableBeanFactory} interface, or does not hold an
     * autowire-capable bean factory yet (e.g. if {@code refresh()} has
     * never been called), or if the context has been closed already
     * @see ConfigurableApplicationContext#refresh()
     * @see ConfigurableApplicationContext#getBeanFactory()
     */
    AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

}

ApplicationContext是spring中較高級的容器。和BeanFactory類似,它可以加載配置文件中定義的bean,將所有的bean集中在一起,當有請求的時候分配bean。 另外,它增加了企業所需要的功能,比如,從屬性文件從解析文本信息和將事件傳遞給所指定的監聽器。這個容器在org.springframework.context.ApplicationContext接口中定義。ApplicationContext包含BeanFactory所有的功能,一般情況下,相對於BeanFactory,ApplicationContext會被推薦使用。但BeanFactory仍然可以在輕量級應用中使用,比如移動設備或者基於applet的應用程序。

ApplicationContext接口關係

1、訪問應用程序組件的Bean工廠方法。繼承自ListableBeanFactory。
2、訪問資源。這一特性主要體現在ResourcePatternResolver接口上,對Resource和ResourceLoader的支持,這樣我們可以從不同地方得到Bean定義資源。這種抽象使用戶程序可以靈活地定義Bean定義信息,尤其是從不同的IO途徑得到Bean定義信息。這在接口上看不出來,不過一般來說,具體ApplicationContext都是繼承了DefaultResourceLoader的子類。因爲DefaultResourceLoader是AbstractApplicationContext的基類。
3、支持應用事件。繼承了接口ApplicationEventPublisher,爲應用環境引入了事件機制,這些事件和Bean的生命週期的結合爲Bean的管理提供了便利。
4、解析消息的能力,支持國際化。繼承MessageSource。
5、從父上下文繼承。在後代的定義將始終優先。這意味着,例如,一個上下文可以被整個Web應用程序使用,而每個servlet都可以使用獨立於任何其他servlet的子環境。

ApplicationContext繼承體系

這裏寫圖片描述

ApplicationContext容器實現類

常用的如下:

AnnotationConfigApplicationContext

從一個或者多個基於java的配置類中加載Spring應用上下文。例如:

 ApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(test.class);

AnnotationConfigWebApplicationContext

加載spring web應用上下文。

ClassPathXmlApplicationContext

從類的路徑下的一個或多個XML配置文件中加載上下文,把應用上下文的定義文件作爲類資源

FileSystemXmlApplicationContext

和ClassPathXmlApplicationContext的區別在於後者是從指定的文件系統路徑下查找配置文件,而前者是在所有的類路徑下查找配置文件。
例如:

ApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("c:/user/pro.xml");

ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("pro.xml");

容器的運作原理

下面就上述提到的FileSystemXmlApplicationContext的容器實現類說明容器運作原理。

FileSystemXmlApplicationContext源碼

package org.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * Standalone XML application context, taking the context definition files
 * from the file system or from URLs, interpreting plain paths as relative
 * file system locations (e.g. "mydir/myfile.txt"). Useful for test harnesses
 * as well as for standalone environments.
 *
 * <p><b>NOTE:</b> Plain paths will always be interpreted as relative
 * to the current VM working directory, even if they start with a slash.
 * (This is consistent with the semantics in a Servlet container.)
 * <b>Use an explicit "file:" prefix to enforce an absolute file path.</b>
 *
 * <p>The config location defaults can be overridden via {@link #getConfigLocations},
 * Config locations can either denote concrete files like "/myfiles/context.xml"
 * or Ant-style patterns like "/myfiles/*-context.xml" (see the
 * {@link org.springframework.util.AntPathMatcher} javadoc for pattern details).
 *
 * <p>Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files. This can be leveraged to
 * deliberately override certain bean definitions via an extra XML file.
 *
 * <p><b>This is a simple, one-stop shop convenience ApplicationContext.
 * Consider using the {@link GenericApplicationContext} class in combination
 * with an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}
 * for more flexible context setup.</b>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see #getResource
 * @see #getResourceByPath
 * @see GenericApplicationContext
 */
public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {

    /**
     * Create a new FileSystemXmlApplicationContext for bean-style configuration.
     * @see #setConfigLocation
     * @see #setConfigLocations
     * @see #afterPropertiesSet()
     */
    public FileSystemXmlApplicationContext() {
    }

    /**
     * Create a new FileSystemXmlApplicationContext for bean-style configuration.
     * @param parent the parent context
     * @see #setConfigLocation
     * @see #setConfigLocations
     * @see #afterPropertiesSet()
     */
    public FileSystemXmlApplicationContext(ApplicationContext parent) {
        super(parent);
    }

    /**
     * Create a new FileSystemXmlApplicationContext, loading the definitions
     * from the given XML file and automatically refreshing the context.
     * @param configLocation file path
     * @throws BeansException if context creation failed
     */
    public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[] {configLocation}, true, null);
    }

    /**
     * Create a new FileSystemXmlApplicationContext, loading the definitions
     * from the given XML files and automatically refreshing the context.
     * @param configLocations array of file paths
     * @throws BeansException if context creation failed
     */
    public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
        this(configLocations, true, null);
    }

    /**
     * Create a new FileSystemXmlApplicationContext with the given parent,
     * loading the definitions from the given XML files and automatically
     * refreshing the context.
     * @param configLocations array of file paths
     * @param parent the parent context
     * @throws BeansException if context creation failed
     */
    public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
        this(configLocations, true, parent);
    }

    /**
     * Create a new FileSystemXmlApplicationContext, loading the definitions
     * from the given XML files.
     * @param configLocations array of file paths
     * @param refresh whether to automatically refresh the context,
     * loading all bean definitions and creating all singletons.
     * Alternatively, call refresh manually after further configuring the context.
     * @throws BeansException if context creation failed
     * @see #refresh()
     */
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
        this(configLocations, refresh, null);
    }

    /**
     * Create a new FileSystemXmlApplicationContext with the given parent,
     * loading the definitions from the given XML files.
     * @param configLocations array of file paths
     * @param refresh whether to automatically refresh the context,
     * loading all bean definitions and creating all singletons.
     * Alternatively, call refresh manually after further configuring the context.
     * @param parent the parent context
     * @throws BeansException if context creation failed
     * @see #refresh()
     */
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }


    /**
     * Resolve resource paths as file system paths.
     * <p>Note: Even if a given path starts with a slash, it will get
     * interpreted as relative to the current VM working directory.
     * This is consistent with the semantics in a Servlet container.
     * @param path path to the resource
     * @return Resource handle
     * @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
     */
    @Override
    protected Resource getResourceByPath(String path) {
        if (path != null && path.startsWith("/")) {
            path = path.substring(1);
        }
        return new FileSystemResource(path);
    }

}

編寫測試類

public class FileSystemXmlApplicationContextTest{

    public static void main(String[] args) {
        ApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("c:/user/pro.xml");
        fileSystemXmlApplicationContext.getBean("test", Test.class);
    }
 }

源碼追蹤分析

/**
     * Create a new FileSystemXmlApplicationContext with the given parent,
     * loading the definitions from the given XML files.
     * @param configLocations array of file paths
     * @param refresh whether to automatically refresh the context,
     * loading all bean definitions and creating all singletons.
     * Alternatively, call refresh manually after further configuring the context.
     * @param parent the parent context
     * @throws BeansException if context creation failed
     * @see #refresh()
     */
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }

通過分析FileSystemXmlApplicationContext的源代碼可以知道,在創建FileSystemXmlApplicationContext容器時,構造方法做以下兩項重要工作:

首先,調用父類容器的構造方法(super(parent)方法)爲容器設置好Bean資源加載器。

/**
     * Create a new AbstractApplicationContext with the given parent context.
     * @param parent the parent context
     */
    public AbstractApplicationContext(ApplicationContext parent) {
        this();
        setParent(parent);
    }

然後,setConfigLocations(configLocations);主要是加載配置文件的路徑。

/**
     * Set the config locations for this application context.
     * <p>If not set, the implementation may use a default as appropriate.
     */
    public void setConfigLocations(String... locations) {
        if (locations != null) {
            Assert.noNullElements(locations, "Config locations must not be null");
            this.configLocations = new String[locations.length];
            for (int i = 0; i < locations.length; i++) {
                this.configLocations[i] = resolvePath(locations[i]).trim();
            }
        }
        else {
            this.configLocations = null;
        }
    }

最主要的是refresh();方法的實現。Ioc容器的refresh()過程,是個非常複雜的過程,但不同的容器實現這裏都是相似的,因此基類中就將他們封裝好了。
我們繼續跟進refresh()方法

@Override
    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) {
                logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

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

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

refresh定義在AbstractApplicationContext類中,它詳細描述了整個ApplicationContext的初始化過程,比如BeanFactory的更新、MessageSource和PostProcessor的註冊等。這裏看起來像是對ApplicationContext進行初始化的模版或執行提綱,這個執行過程爲Bean的生命週期管理提供了條件。

/**
     * Prepare this context for refreshing, setting its startup date and
     * active flag as well as performing any initialization of property sources.
     */
    protected void prepareRefresh() {
        this.startupDate = System.currentTimeMillis();
        this.active.set(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
        getEnvironment().validateRequiredProperties();
    }

走到這裏prepareRefresh()方法主要是爲準備刷新容器, 獲取容器的當時時間, 同時給容器設置同步標識 。
繼續往下走obtainFreshBeanFactory();

/**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

看看refreshBeanFactory();幹了些什麼

/**
     * This implementation performs an actual refresh of this context's underlying
     * bean factory, shutting down the previous bean factory (if any) and
     * initializing a fresh bean factory for the next phase of the context's lifecycle.
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) { //如果已經有容器,銷燬容器中的bean,關閉容器  
            destroyBeans();
            closeBeanFactory();
        }
        try {
            //創建IoC容器  
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            //對IoC容器進行定製化,如設置啓動參數,開啓註解的自動裝配等  
            customizeBeanFactory(beanFactory);
            //調用載入Bean定義的方法,在當前類中只定義了抽象的loadBeanDefinitions方法,具體的實現調用子類容器  
            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是否存在,如果存在則先銷燬beans並關閉beanFactory,接着創建DefaultListableBeanFactory,並調用loadBeanDefinitions(beanFactory)裝載bean。

接着跟進loadBeanDefinitions()方法:
AbstractRefreshableApplicationContext中只定義了抽象的loadBeanDefinitions方法,容器真正調用的是其子類AbstractXmlApplicationContext對該方法的實現,AbstractXmlApplicationContext的主要源碼如下:

/**
     * Loads the bean definitions via an XmlBeanDefinitionReader.
     * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        //創建XmlBeanDefinitionReader,即創建Bean讀取器,並通過回調設置到容器中去,容  器使用該讀取器讀取Bean定義資源  
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        //爲Bean讀取器設置Spring資源加載器,AbstractXmlApplicationContext的  
        //祖先父類AbstractApplicationContext繼承DefaultResourceLoader,因此,容器本身也是一個資源加載器 
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
         //爲Bean讀取器設置SAX xml解析器  
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        //當Bean讀取器讀取Bean定義的Xml資源文件時,啓用Xml的校驗機制 
        initBeanDefinitionReader(beanDefinitionReader);
        //Bean讀取器真正實現加載的方法  
        loadBeanDefinitions(beanDefinitionReader);
    }

看下執行:
這裏寫圖片描述

Xml Bean讀取器(XmlBeanDefinitionReader)調用其父類AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法讀取Bean定義資源。

下面將繼續研究讀取Bean定義資源的部分:

BeanDefinitionReader在其抽象父類AbstractBeanDefinitionReader中定義了載入過程

//重載方法,調用下面的loadBeanDefinitions(String, Set<Resource>);方法  
   public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {  
       return loadBeanDefinitions(location, null);  
   }  
   public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {  
       //獲取在IoC容器初始化過程中設置的資源加載器  
       ResourceLoader resourceLoader = getResourceLoader();  
       if (resourceLoader == null) {  
           throw new BeanDefinitionStoreException(  
                   "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");  
       }  
       if (resourceLoader instanceof ResourcePatternResolver) {  
           try {  
               //將指定位置的Bean定義資源文件解析爲Spring IoC容器封裝的資源  
               //加載多個指定位置的Bean定義資源文件  
               Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);  
               //委派調用其子類XmlBeanDefinitionReader的方法,實現加載功能  
               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 {  
           //將指定位置的Bean定義資源文件解析爲Spring IoC容器封裝的資源  
           //加載單個指定位置的Bean定義資源文件  
           Resource resource = resourceLoader.getResource(location);  
           //委派調用其子類XmlBeanDefinitionReader的方法,實現加載功能  
           int loadCount = loadBeanDefinitions(resource);  
           if (actualResources != null) {  
               actualResources.add(resource);  
           }  
           if (logger.isDebugEnabled()) {  
               logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");  
           }  
           return loadCount;  
       }  
   }  
   //重載方法,調用loadBeanDefinitions(String);  
   public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {  
       Assert.notNull(locations, "Location array must not be null");  
       int counter = 0;  
       for (String location : locations) {  
           counter += loadBeanDefinitions(location);  
       }  
       return counter;  
    }

loadBeanDefinitions(Resource…resources)方法和上面分析的3個方法類似,同樣也是調用XmlBeanDefinitionReader的loadBeanDefinitions方法。

從對AbstractBeanDefinitionReader的loadBeanDefinitions方法源碼分析可以看出該方法做了以下兩件事:

首先,調用資源加載器的獲取資源方法resourceLoader.getResource(location),獲取到要加載的資源。

其次,真正執行加載功能是其子類XmlBeanDefinitionReader的loadBeanDefinitions方法。
這裏寫圖片描述

XmlBeanDefinitionReader通過調用其父類DefaultResourceLoader的getResource方法獲取要加載的資源,其源碼如下

//獲取Resource的具體實現方法  
   public Resource getResource(String location) {  
       Assert.notNull(location, "Location must not be null");  
       //如果是類路徑的方式,那需要使用ClassPathResource 來得到bean 文件的資源對象  
       if (location.startsWith(CLASSPATH_URL_PREFIX)) {  
           return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());  
       }  
        try {  
             // 如果是URL 方式,使用UrlResource 作爲bean 文件的資源對象  
            URL url = new URL(location);  
            return new UrlResource(url);  
           }  
           catch (MalformedURLException ex) { 
           } 
           //如果既不是classpath標識,又不是URL標識的Resource定位,則調用  
           //容器本身的getResourceByPath方法獲取Resource  
           return getResourceByPath(location);  

   }

FileSystemXmlApplicationContext容器提供了getResourceByPath方法的實現,就是爲了處理既不是classpath標識,又不是URL標識的Resource定位這種情況。

protected Resource getResourceByPath(String path) {    
   if (path != null && path.startsWith("/")) {    
        path = path.substring(1);    
    }  
    //這裏使用文件系統資源對象來定義bean 文件
    return new FileSystemResource(path);  
}

這樣代碼就回到了 FileSystemXmlApplicationContext 中來,他提供了FileSystemResource 來完成從文件系統得到配置文件的資源定義。

這樣,就可以從文件系統路徑上對IOC 配置文件進行加載 - 當然我們可以按照這個邏輯從任何地方加載,在Spring 中我們看到它提供 的各種資源抽象,比如ClassPathResource, URLResource,FileSystemResource 等來供我們使用。上面我們看到的是定位Resource 的一個過程,而這只是加載過程的一部分.

XmlBeanDefinitionReader加載Bean定義資源:

Bean定義的Resource得到了
繼續回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean文件的資源定義以後的載入過程。

//XmlBeanDefinitionReader加載資源的入口方法  
   public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {  
       //將讀入的XML資源進行特殊編碼處理  
       return loadBeanDefinitions(new EncodedResource(resource));  
   } 
     //這裏是載入XML形式Bean定義資源文件方法
   public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {    
   .......    
   try {    
        //將資源文件轉爲InputStream的IO流 
       InputStream inputStream = encodedResource.getResource().getInputStream();    
       try {    
          //從InputStream中得到XML的解析源    
           InputSource inputSource = new InputSource(inputStream);    
           if (encodedResource.getEncoding() != null) {    
               inputSource.setEncoding(encodedResource.getEncoding());    
           }    
           //這裏是具體的讀取過程    
           return doLoadBeanDefinitions(inputSource, encodedResource.getResource());    
       }    
       finally {    
           //關閉從Resource中得到的IO流    
           inputStream.close();    
       }    
   }    
      .........    
26}    
   //從特定XML文件中實際載入Bean定義資源的方法 
   protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)    
       throws BeanDefinitionStoreException {    
   try {    
       int validationMode = getValidationModeForResource(resource);    
       //將XML文件轉換爲DOM對象,解析過程由documentLoader實現    
       Document doc = this.documentLoader.loadDocument(    
               inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);    
       //這裏是啓動對Bean定義解析的詳細過程,該解析過程會用到Spring的Bean配置規則
       return registerBeanDefinitions(doc, resource);    
     }    
     .......    
     }

通過源碼分析,載入Bean定義資源文件的最後一步是將Bean定義資源轉換爲Document對象,該過程由documentLoader實現
DocumentLoader將Bean定義資源轉換成Document對象的源碼如下:

//使用標準的JAXP將載入的Bean定義資源轉換成document對象  
   public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,  
           ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {  
       //創建文件解析器工廠  
       DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);  
       if (logger.isDebugEnabled()) {  
           logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");  
       }  
       //創建文檔解析器  
       DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);  
       //解析Spring的Bean定義資源  
       return builder.parse(inputSource);  
   }  
   protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)  
           throws ParserConfigurationException {  
       //創建文檔解析工廠  
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
       factory.setNamespaceAware(namespaceAware);  
       //設置解析XML的校驗  
       if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {  
           factory.setValidating(true);  
           if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {  
               factory.setNamespaceAware(true);  
               try {  
                   factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);  
               }  
               catch (IllegalArgumentException ex) {  
                   ParserConfigurationException pcex = new ParserConfigurationException(  
                           "Unable to validate using XSD: Your JAXP provider [" + factory +  
                           "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +  
                           "Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");  
                   pcex.initCause(ex);  
                   throw pcex;  
               }  
           }  
       }  
       return factory;  
   }

該解析過程調用JavaEE標準的JAXP標準進行處理。
至此Spring IoC容器根據定位的Bean定義資源文件,將其加載讀入並轉換成爲Document對象過程完成。

接下來我們要繼續分析Spring IoC容器將載入的Bean定義資源文件轉換爲Document對象之後,是如何將其解析爲Spring IoC管理的Bean對象並將其註冊到容器中的。

XmlBeanDefinitionReader類中的doLoadBeanDefinitions方法是從特定XML文件中實際載入Bean定義資源的方法,該方法在載入Bean定義資源之後將其轉換爲Document對象,接下來調用registerBeanDefinitions啓動Spring IoC容器對Bean定義的解析過程,registerBeanDefinitions方法源碼如下:

//按照Spring的Bean語義要求將Bean定義資源解析並轉換爲容器內部數據結構  
   public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {  
       //得到BeanDefinitionDocumentReader來對xml格式的BeanDefinition解析  
       BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();  
       //獲得容器中註冊的Bean數量  
       int countBefore = getRegistry().getBeanDefinitionCount();  
       //解析過程入口,這裏使用了委派模式,BeanDefinitionDocumentReader只是個接口,//具體的解析實現過程有實現類DefaultBeanDefinitionDocumentReader完成  
       documentReader.registerBeanDefinitions(doc, createReaderContext(resource));  
       //統計解析的Bean數量  
       return getRegistry().getBeanDefinitionCount() - countBefore;  
   }  
   //創建BeanDefinitionDocumentReader對象,解析Document對象  
   protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {  
       return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));  
      }

Bean定義資源的載入解析分爲以下兩個過程:

首先,通過調用XML解析器將Bean定義資源文件轉換得到Document對象,但是這些Document對象並沒有按照Spring的Bean規則進行解析。這一步是載入的過程

其次,在完成通用的XML解析之後,按照Spring的Bean規則對Document對象進行解析。

按照Spring的Bean規則對Document對象解析的過程是在接口BeanDefinitionDocumentReader的實現類DefaultBeanDefinitionDocumentReader中實現的。

BeanDefinitionDocumentReader接口通過registerBeanDefinitions方法調用其實現類DefaultBeanDefinitionDocumentReader對Document對象進行解析,解析的代碼如下:

//根據Spring DTD對Bean的定義規則解析Bean定義Document對象  
    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {  
        //獲得XML描述符  
        this.readerContext = readerContext;  
        logger.debug("Loading bean definitions");  
        //獲得Document的根元素  
        Element root = doc.getDocumentElement();  
        //具體的解析過程由BeanDefinitionParserDelegate實現,  
        //BeanDefinitionParserDelegate中定義了Spring Bean定義XML文件的各種元素  
       BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);  
       //在解析Bean定義之前,進行自定義的解析,增強解析過程的可擴展性  
       preProcessXml(root);  
       //從Document的根元素開始進行Bean定義的Document對象  
       parseBeanDefinitions(root, delegate);  
       //在解析Bean定義之後,進行自定義的解析,增加解析過程的可擴展性  
       postProcessXml(root);  
   }  
   //創建BeanDefinitionParserDelegate,用於完成真正的解析過程  
   protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) {  
       BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);  
       //BeanDefinitionParserDelegate初始化Document根元素  
       delegate.initDefaults(root);  
       return delegate;  
   }  
   //使用Spring的Bean規則從Document的根元素開始進行Bean定義的Document對象  
   protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {  
       //Bean定義的Document對象使用了Spring默認的XML命名空間  
       if (delegate.isDefaultNamespace(root)) {  
           //獲取Bean定義的Document對象根元素的所有子節點  
           NodeList nl = root.getChildNodes();  
           for (int i = 0; i < nl.getLength(); i++) {  
               Node node = nl.item(i);  
               //獲得Document節點是XML元素節點  
               if (node instanceof Element) {  
                   Element ele = (Element) node;  
               //Bean定義的Document的元素節點使用的是Spring默認的XML命名空間  
                   if (delegate.isDefaultNamespace(ele)) {  
                       //使用Spring的Bean規則解析元素節點  
                       parseDefaultElement(ele, delegate);  
                   }  
                   else {  
                       //沒有使用Spring默認的XML命名空間,則使用用戶自定義的解//析規則解析元素節點  
                       delegate.parseCustomElement(ele);  
                   }  
               }  
           }  
       }  
       else {  
           //Document的根節點沒有使用Spring默認的命名空間,則使用用戶自定義的  
           //解析規則解析Document根節點  
           delegate.parseCustomElement(root);  
       }  
   }  
   //使用Spring的Bean規則解析Document元素節點  
   private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {  
       //如果元素節點是<Import>導入元素,進行導入解析  
       if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {  
           importBeanDefinitionResource(ele);  
       }  
       //如果元素節點是<Alias>別名元素,進行別名解析  
       else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {  
           processAliasRegistration(ele);  
       }  
       //元素節點既不是導入元素,也不是別名元素,即普通的<Bean>元素,  
       //按照Spring的Bean規則解析元素  
       else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {  
           processBeanDefinition(ele, delegate);  
       }  
   }  
   //解析<Import>導入元素,從給定的導入路徑加載Bean定義資源到Spring IoC容器中  
   protected void importBeanDefinitionResource(Element ele) {  
       //獲取給定的導入元素的location屬性  
       String location = ele.getAttribute(RESOURCE_ATTRIBUTE);  
       //如果導入元素的location屬性值爲空,則沒有導入任何資源,直接返回  
       if (!StringUtils.hasText(location)) {  
           getReaderContext().error("Resource location must not be empty", ele);  
           return;  
       }  
       //使用系統變量值解析location屬性值  
       location = SystemPropertyUtils.resolvePlaceholders(location);  
       Set<Resource> actualResources = new LinkedHashSet<Resource>(4);  
       //標識給定的導入元素的location是否是絕對路徑  
       boolean absoluteLocation = false;  
       try {  
           absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();  
       }  
       catch (URISyntaxException ex) {  
           //給定的導入元素的location不是絕對路徑  
       }  
       //給定的導入元素的location是絕對路徑  
       if (absoluteLocation) {  
           try {  
               //使用資源讀入器加載給定路徑的Bean定義資源  
               int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);  
               if (logger.isDebugEnabled()) {  
                   logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");  
               }  
           }  
           catch (BeanDefinitionStoreException ex) {  
               getReaderContext().error(  
                       "Failed to import bean definitions from URL location [" + location + "]", ele, ex);  
           }  
       }  
       else {  
           //給定的導入元素的location是相對路徑  
           try {  
               int importCount;  
               //將給定導入元素的location封裝爲相對路徑資源  
               Resource relativeResource = getReaderContext().getResource().createRelative(location);  
               //封裝的相對路徑資源存在  
               if (relativeResource.exists()) {  
                   //使用資源讀入器加載Bean定義資源  
                   importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);  
                   actualResources.add(relativeResource);  
               }  
               //封裝的相對路徑資源不存在  
               else {  
                   //獲取Spring IoC容器資源讀入器的基本路徑  
                   String baseLocation = getReaderContext().getResource().getURL().toString();  
                   //根據Spring IoC容器資源讀入器的基本路徑加載給定導入  
                   //路徑的資源  
                   importCount = getReaderContext().getReader().loadBeanDefinitions(  
                           StringUtils.applyRelativePath(baseLocation, location), actualResources);  
               }  
               if (logger.isDebugEnabled()) {  
                   logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");  
               }  
           }  
           catch (IOException ex) {  
               getReaderContext().error("Failed to resolve current resource location", ele, ex);  
           }  
           catch (BeanDefinitionStoreException ex) {  
               getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",  
                       ele, ex);  
           }  
       }  
       Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);  
       //在解析完<Import>元素之後,發送容器導入其他資源處理完成事件  
       getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));  
   }  
   //解析<Alias>別名元素,爲Bean向Spring IoC容器註冊別名  
   protected void processAliasRegistration(Element ele) {  
       //獲取<Alias>別名元素中name的屬性值  
       String name = ele.getAttribute(NAME_ATTRIBUTE);  
       //獲取<Alias>別名元素中alias的屬性值  
       String alias = ele.getAttribute(ALIAS_ATTRIBUTE);  
       boolean valid = true;  
       //<alias>別名元素的name屬性值爲空  
       if (!StringUtils.hasText(name)) {  
           getReaderContext().error("Name must not be empty", ele);  
           valid = false;  
       }  
       //<alias>別名元素的alias屬性值爲空  
       if (!StringUtils.hasText(alias)) {  
           getReaderContext().error("Alias must not be empty", ele);  
           valid = false;  
       }  
       if (valid) {  
           try {  
               //向容器的資源讀入器註冊別名  
               getReaderContext().getRegistry().registerAlias(name, alias);  
           }  
           catch (Exception ex) {  
               getReaderContext().error("Failed to register alias '" + alias +  
                       "' for bean with name '" + name + "'", ele, ex);  
           }  
           //在解析完<Alias>元素之後,發送容器別名處理完成事件  
           getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));  
       }  
   }  
   //解析Bean定義資源Document對象的普通元素  
   protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {  
       // BeanDefinitionHolder是對BeanDefinition的封裝,即Bean定義的封裝類  
       //對Document對象中<Bean>元素的解析由BeanDefinitionParserDelegate實現  BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);  
       if (bdHolder != null) {  
           bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);  
           try {  
              //向Spring IoC容器註冊解析得到的Bean定義,這是Bean定義向IoC容器註冊的入口            
                  BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());  
           }  
           catch (BeanDefinitionStoreException ex) {  
               getReaderContext().error("Failed to register bean definition with name '" +  
                       bdHolder.getBeanName() + "'", ele, ex);  
           }  
           //在完成向Spring IoC容器註冊解析得到的Bean定義之後,發送註冊事件  
           getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));  
       }  
   }

通過上述Spring IoC容器對載入的Bean定義Document解析可以看出,我們使用Spring時,在Spring配置文件中可以使用元素來導入IoC容器所需要的其他資源,Spring IoC容器在解析時會首先將指定導入的資源加載進容器中。使用別名時,Spring IoC容器首先將別名元素所定義的別名註冊到容器中。

對於既不是元素,又不是元素的元素,即Spring配置文件中普通的元素的解析由BeanDefinitionParserDelegate類的parseBeanDefinitionElement方法來實現。

Bean定義資源文件中的和元素解析在DefaultBeanDefinitionDocumentReader中已經完成,對Bean定義資源文件中使用最多的元素交由BeanDefinitionParserDelegate來解析,其解析實現的源碼如下:

//解析<Bean>元素的入口  
   public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {  
       return parseBeanDefinitionElement(ele, null);  
   }  
   //解析Bean定義資源文件中的<Bean>元素,這個方法中主要處理<Bean>元素的id,name  
   //和別名屬性  
   public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {  
       //獲取<Bean>元素中的id屬性值  
       String id = ele.getAttribute(ID_ATTRIBUTE);  
       //獲取<Bean>元素中的name屬性值  
       String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);  
       ////獲取<Bean>元素中的alias屬性值  
       List<String> aliases = new ArrayList<String>();  
       //將<Bean>元素中的所有name屬性值存放到別名中  
       if (StringUtils.hasLength(nameAttr)) {  
           String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS);  
           aliases.addAll(Arrays.asList(nameArr));  
       }  
       String beanName = id;  
       //如果<Bean>元素中沒有配置id屬性時,將別名中的第一個值賦值給beanName  
       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");  
           }  
       }  
       //檢查<Bean>元素所配置的id或者name的唯一性,containingBean標識<Bean>  
       //元素中是否包含子<Bean>元素  
       if (containingBean == null) {  
           //檢查<Bean>元素所配置的id、name或者別名是否重複  
           checkNameUniqueness(beanName, aliases, ele);  
       }  
       //詳細對<Bean>元素中配置的Bean定義進行解析的地方  
       AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);  
       if (beanDefinition != null) {  
           if (!StringUtils.hasText(beanName)) {  
               try {  
                   if (containingBean != null) {  
                       //如果<Bean>元素中沒有配置id、別名或者name,且沒有包含子//<Bean>元素,爲解析的Bean生成一個唯一beanName並註冊  
                       beanName = BeanDefinitionReaderUtils.generateBeanName(  
                               beanDefinition, this.readerContext.getRegistry(), true);  
                   }  
                   else {  
                       //如果<Bean>元素中沒有配置id、別名或者name,且包含了子//<Bean>元素,爲解析的Bean使用別名向IoC容器註冊  
                       beanName = this.readerContext.generateBeanName(beanDefinition);  
                       //爲解析的Bean使用別名註冊時,爲了向後兼容                                    //Spring1.2/2.0,給別名添加類名後綴  
                       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);  
       }  
       //當解析出錯時,返回null  
       return null;  
   }  
   //詳細對<Bean>元素中配置的Bean定義其他屬性進行解析,由於上面的方法中已經對//Bean的id、name和別名等屬性進行了處理,該方法中主要處理除這三個以外的其他屬性數據  
   public AbstractBeanDefinition parseBeanDefinitionElement(  
           Element ele, String beanName, BeanDefinition containingBean) {  
       //記錄解析的<Bean>  
       this.parseState.push(new BeanEntry(beanName));  
       //這裏只讀取<Bean>元素中配置的class名字,然後載入到BeanDefinition中去  
       //只是記錄配置的class名字,不做實例化,對象的實例化在依賴注入時完成  
       String className = null;  
       if (ele.hasAttribute(CLASS_ATTRIBUTE)) {  
           className = ele.getAttribute(CLASS_ATTRIBUTE).trim();  
       }  
       try {  
           String parent = null;  
           //如果<Bean>元素中配置了parent屬性,則獲取parent屬性的值  
           if (ele.hasAttribute(PARENT_ATTRIBUTE)) {  
               parent = ele.getAttribute(PARENT_ATTRIBUTE);  
           }  
           //根據<Bean>元素配置的class名稱和parent屬性值創建BeanDefinition  
           //爲載入Bean定義信息做準備  
           AbstractBeanDefinition bd = createBeanDefinition(className, parent);  
           //對當前的<Bean>元素中配置的一些屬性進行解析和設置,如配置的單態(singleton)屬性等  
           parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);  
           //爲<Bean>元素解析的Bean設置description信息 bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));  
           //對<Bean>元素的meta(元信息)屬性解析  
           parseMetaElements(ele, bd);  
           //對<Bean>元素的lookup-method屬性解析  
           parseLookupOverrideSubElements(ele, bd.getMethodOverrides());  
           //對<Bean>元素的replaced-method屬性解析  
           parseReplacedMethodSubElements(ele, bd.getMethodOverrides());  
           //解析<Bean>元素的構造方法設置  
           parseConstructorArgElements(ele, bd);  
           //解析<Bean>元素的<property>設置  
           parsePropertyElements(ele, bd);  
           //解析<Bean>元素的qualifier屬性  
           parseQualifierElements(ele, bd);  
           //爲當前解析的Bean設置所需的資源和依賴對象  
           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();  
       }  
       //解析<Bean>元素出錯時,返回null  
       return null;  
   }

只要使用過Spring,對Spring配置文件比較熟悉的人,通過對上述源碼的分析,就會明白我們在Spring配置文件中元素的中配置的屬性就是通過該方法解析和設置到Bean中去的。

注意:在解析元素過程中沒有創建和實例化Bean對象,只是創建了Bean對象的定義類BeanDefinition,將元素中的配置信息設置到BeanDefinition中作爲記錄,當依賴注入時才使用這些記錄信息創建和實例化具體的Bean對象。

上面方法中一些對一些配置如元信息(meta)、qualifier等的解析,我們在Spring中配置時使用的也不多,我們在使用Spring的元素時,配置最多的是屬性,因此我們下面繼續分析源碼,瞭解Bean的屬性在解析時是如何設置的。

BeanDefinitionParserDelegate在解析調用parsePropertyElements方法解析元素中的屬性子元素,解析源碼如下:

//解析<Bean>元素中的<property>子元素  
   public void parsePropertyElements(Element beanEle, BeanDefinition bd) {  
       //獲取<Bean>元素中所有的子元素  
       NodeList nl = beanEle.getChildNodes();  
       for (int i = 0; i < nl.getLength(); i++) {  
           Node node = nl.item(i);  
           //如果子元素是<property>子元素,則調用解析<property>子元素方法解析  
           if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {  
               parsePropertyElement((Element) node, bd);  
           }  
       }  
   }  
   //解析<property>元素  
   public void parsePropertyElement(Element ele, BeanDefinition bd) {  
       //獲取<property>元素的名字   
       String propertyName = ele.getAttribute(NAME_ATTRIBUTE);  
       if (!StringUtils.hasLength(propertyName)) {  
           error("Tag 'property' must have a 'name' attribute", ele);  
           return;  
       }  
       this.parseState.push(new PropertyEntry(propertyName));  
       try {  
           //如果一個Bean中已經有同名的property存在,則不進行解析,直接返回。  
           //即如果在同一個Bean中配置同名的property,則只有第一個起作用  
           if (bd.getPropertyValues().contains(propertyName)) {  
               error("Multiple 'property' definitions for property '" + propertyName + "'", ele);  
               return;  
           }  
           //解析獲取property的值  
           Object val = parsePropertyValue(ele, bd, propertyName);  
           //根據property的名字和值創建property實例  
           PropertyValue pv = new PropertyValue(propertyName, val);  
           //解析<property>元素中的屬性  
           parseMetaElements(ele, pv);  
           pv.setSource(extractSource(ele));  
           bd.getPropertyValues().addPropertyValue(pv);  
       }  
       finally {  
           this.parseState.pop();  
       }  
   }  
   //解析獲取property值  
   public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {  
       String elementName = (propertyName != null) ?  
                       "<property> element for property '" + propertyName + "'" :  
                       "<constructor-arg> element";  
       //獲取<property>的所有子元素,只能是其中一種類型:ref,value,list等  
       NodeList nl = ele.getChildNodes();  
       Element subElement = null;  
       for (int i = 0; i < nl.getLength(); i++) {  
           Node node = nl.item(i);  
           //子元素不是description和meta屬性  
           if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&  
                   !nodeNameEquals(node, META_ELEMENT)) {  
               if (subElement != null) {  
                   error(elementName + " must not contain more than one sub-element", ele);  
               }  
               else {//當前<property>元素包含有子元素  
                   subElement = (Element) node;  
               }  
           }  
       }  
       //判斷property的屬性值是ref還是value,不允許既是ref又是value  
       boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);  
       boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);  
       if ((hasRefAttribute && hasValueAttribute) ||  
               ((hasRefAttribute || hasValueAttribute) && subElement != null)) {  
           error(elementName +  
                   " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);  
       }  
       //如果屬性是ref,創建一個ref的數據對象RuntimeBeanReference,這個對象  
       //封裝了ref信息  
       if (hasRefAttribute) {  
           String refName = ele.getAttribute(REF_ATTRIBUTE);  
           if (!StringUtils.hasText(refName)) {  
               error(elementName + " contains empty 'ref' attribute", ele);  
           }  
           //一個指向運行時所依賴對象的引用  
           RuntimeBeanReference ref = new RuntimeBeanReference(refName);  
           //設置這個ref的數據對象是被當前的property對象所引用  
           ref.setSource(extractSource(ele));  
           return ref;  
       }  
        //如果屬性是value,創建一個value的數據對象TypedStringValue,這個對象  
       //封裝了value信息  
       else if (hasValueAttribute) {  
           //一個持有String類型值的對象  
           TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));  
           //設置這個value數據對象是被當前的property對象所引用  
           valueHolder.setSource(extractSource(ele));  
           return valueHolder;  
       }  
       //如果當前<property>元素還有子元素  
       else if (subElement != null) {  
           //解析<property>的子元素  
           return parsePropertySubElement(subElement, bd);  
       }  
       else {  
           //propery屬性中既不是ref,也不是value屬性,解析出錯返回null        error(elementName + " must specify a ref or value", ele);  
           return null;  
       }  
    }

通過對上述源碼的分析,我們可以瞭解在Spring配置文件中,元素中元素的相關配置是如何處理的:

a. ref被封裝爲指向依賴對象一個引用。

b.value配置都會封裝成一個字符串類型的對象。

c.ref和value都通過“解析的數據類型屬性值.setSource(extractSource(ele));”方法將屬性值/引用與所引用的屬性關聯起來。

在方法的最後對於元素的子元素通過parsePropertySubElement 方法解析,我們繼續分析該方法的源碼,瞭解其解析過程。

解析元素的子元素:在BeanDefinitionParserDelegate類中的parsePropertySubElement方法對中的子元素解析,源碼如下:

//解析<property>元素中ref,value或者集合等子元素  
   public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) {  
       //如果<property>沒有使用Spring默認的命名空間,則使用用戶自定義的規則解析//內嵌元素  
       if (!isDefaultNamespace(ele)) {  
           return parseNestedCustomElement(ele, bd);  
       }  
       //如果子元素是bean,則使用解析<Bean>元素的方法解析  
       else if (nodeNameEquals(ele, BEAN_ELEMENT)) {  
           BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);  
           if (nestedBd != null) {  
               nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);  
           }  
           return nestedBd;  
       }  
       //如果子元素是ref,ref中只能有以下3個屬性:bean、local、parent  
       else if (nodeNameEquals(ele, REF_ELEMENT)) {  
           //獲取<property>元素中的bean屬性值,引用其他解析的Bean的名稱  
           //可以不再同一個Spring配置文件中,具體請參考Spring對ref的配置規則  
           String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);  
           boolean toParent = false;  
           if (!StringUtils.hasLength(refName)) {  
                //獲取<property>元素中的local屬性值,引用同一個Xml文件中配置  
                //的Bean的id,local和ref不同,local只能引用同一個配置文件中的Bean  
               refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE);  
               if (!StringUtils.hasLength(refName)) {  
                   //獲取<property>元素中parent屬性值,引用父級容器中的Bean  
                   refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);  
                   toParent = true;  
                   if (!StringUtils.hasLength(refName)) {  
                       error("'bean', 'local' or 'parent' is required for <ref> element", ele);  
                       return null;  
                   }  
               }  
           }  
           //沒有配置ref的目標屬性值  
           if (!StringUtils.hasText(refName)) {  
               error("<ref> element contains empty target attribute", ele);  
               return null;  
           }  
           //創建ref類型數據,指向被引用的對象  
           RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);  
           //設置引用類型值是被當前子元素所引用  
           ref.setSource(extractSource(ele));  
           return ref;  
       }  
       //如果子元素是<idref>,使用解析ref元素的方法解析  
       else if (nodeNameEquals(ele, IDREF_ELEMENT)) {  
           return parseIdRefElement(ele);  
       }  
       //如果子元素是<value>,使用解析value元素的方法解析  
       else if (nodeNameEquals(ele, VALUE_ELEMENT)) {  
           return parseValueElement(ele, defaultValueType);  
       }  
       //如果子元素是null,爲<property>設置一個封裝null值的字符串數據  
       else if (nodeNameEquals(ele, NULL_ELEMENT)) {  
           TypedStringValue nullHolder = new TypedStringValue(null);  
           nullHolder.setSource(extractSource(ele));  
           return nullHolder;  
       }  
       //如果子元素是<array>,使用解析array集合子元素的方法解析  
       else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {  
           return parseArrayElement(ele, bd);  
       }  
       //如果子元素是<list>,使用解析list集合子元素的方法解析  
       else if (nodeNameEquals(ele, LIST_ELEMENT)) {  
           return parseListElement(ele, bd);  
       }  
       //如果子元素是<set>,使用解析set集合子元素的方法解析  
       else if (nodeNameEquals(ele, SET_ELEMENT)) {  
           return parseSetElement(ele, bd);  
       }  
       //如果子元素是<map>,使用解析map集合子元素的方法解析  
       else if (nodeNameEquals(ele, MAP_ELEMENT)) {  
           return parseMapElement(ele, bd);  
       }  
       //如果子元素是<props>,使用解析props集合子元素的方法解析  
       else if (nodeNameEquals(ele, PROPS_ELEMENT)) {  
           return parsePropsElement(ele);  
       }  
       //既不是ref,又不是value,也不是集合,則子元素配置錯誤,返回null  
       else {  
           error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);  
           return null;  
       }  
    }

通過上述源碼分析,我們明白了在Spring配置文件中,對元素中配置的Array、List、Set、Map、Prop等各種集合子元素的都通過上述方法解析,生成對應的數據對象,比如ManagedList、ManagedArray、ManagedSet等,這些Managed類是Spring對象BeanDefiniton的數據封裝,對集合數據類型的具體解析有各自的解析方法實現,解析方法的命名非常規範,一目瞭然,我們對集合元素的解析方法進行源碼分析,瞭解其實現過程。

解析子元素:在BeanDefinitionParserDelegate類中的parseListElement方法就是具體實現解析元素中的集合子元素,源碼如下:

//解析<list>集合子元素  
   public List parseListElement(Element collectionEle, BeanDefinition bd) {  
       //獲取<list>元素中的value-type屬性,即獲取集合元素的數據類型  
       String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);  
       //獲取<list>集合元素中的所有子節點  
       NodeList nl = collectionEle.getChildNodes();  
       //Spring中將List封裝爲ManagedList  
       ManagedList<Object> target = new ManagedList<Object>(nl.getLength());  
       target.setSource(extractSource(collectionEle));  
       //設置集合目標數據類型  
       target.setElementTypeName(defaultElementType);  
       target.setMergeEnabled(parseMergeAttribute(collectionEle));  
       //具體的<list>元素解析  
       parseCollectionElements(nl, target, bd, defaultElementType);  
       return target;  
   }   
   //具體解析<list>集合元素,<array>、<list>和<set>都使用該方法解析  
   protected void parseCollectionElements(  
           NodeList elementNodes, Collection<Object> target, BeanDefinition bd, String defaultElementType) {  
       //遍歷集合所有節點  
       for (int i = 0; i < elementNodes.getLength(); i++) {  
           Node node = elementNodes.item(i);  
           //節點不是description節點  
           if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {  
               //將解析的元素加入集合中,遞歸調用下一個子元素  
               target.add(parsePropertySubElement((Element) node, bd, defaultElementType));  
           }  
       }  
    }

經過對Spring Bean定義資源文件轉換的Document對象中的元素層層解析,Spring IoC現在已經將XML形式定義的Bean定義資源文件轉換爲Spring IoC所識別的數據結構——BeanDefinition,它是Bean定義資源文件中配置的POJO對象在Spring IoC容器中的映射,我們可以通過AbstractBeanDefinition爲入口,榮IoC容器進行索引、查詢和操作。

通過Spring IoC容器對Bean定義資源的解析後,IoC容器大致完成了管理Bean對象的準備工作,即初始化過程,但是最爲重要的依賴注入還沒有發生,現在在IoC容器中BeanDefinition存儲的只是一些靜態信息,接下來需要向容器註冊Bean定義信息才能全部完成IoC容器的初始化過程

解析過後的BeanDefinition在IoC容器中的註冊:
讓我們繼續跟蹤程序的執行順序,接下來會到我們第3步中分析DefaultBeanDefinitionDocumentReader對Bean定義轉換的Document對象解析的流程中,在其parseDefaultElement方法中完成對Document對象的解析後得到封裝BeanDefinition的BeanDefinitionHold對象,然後調用BeanDefinitionReaderUtils的registerBeanDefinition方法向IoC容器註冊解析的Bean,BeanDefinitionReaderUtils的註冊的源碼如下:

//將解析的BeanDefinitionHold註冊到容器中 
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)  
    throws BeanDefinitionStoreException {  
        //獲取解析的BeanDefinition的名稱
         String beanName = definitionHolder.getBeanName();  
        //向IoC容器註冊BeanDefinition 
        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());  
        //如果解析的BeanDefinition有別名,向容器爲其註冊別名  
         String[] aliases = definitionHolder.getAliases();  
        if (aliases != null) {  
            for (String aliase : aliases) {  
                registry.registerAlias(beanName, aliase);  
            }  
        }  
}

當調用BeanDefinitionReaderUtils向IoC容器註冊解析的BeanDefinition時,真正完成註冊功能的是DefaultListableBeanFactory。

DefaultListableBeanFactory向IoC容器註冊解析後的BeanDefinition:
DefaultListableBeanFactory中使用一個HashMap的集合對象存放IoC容器中註冊解析的BeanDefinition,向IoC容器註冊的主要源碼如下:

//存儲註冊的俄BeanDefinition  
   private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();  
   //向IoC容器註冊解析的BeanDefiniton  
   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");  
       //校驗解析的BeanDefiniton  
       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);  
           //檢查是否有同名的BeanDefinition已經在IoC容器中註冊,如果已經註冊,  
           //並且不允許覆蓋已註冊的Bean,則拋出註冊失敗異常  
           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 {//如果允許覆蓋,則同名的Bean,後註冊的覆蓋先註冊的  
                   if (this.logger.isInfoEnabled()) {  
                       this.logger.info("Overriding bean definition for bean '" + beanName +  
                               "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");  
                   }  
               }  
           }  
           //IoC容器中沒有已經註冊同名的Bean,按正常註冊流程註冊  
           else {  
               this.beanDefinitionNames.add(beanName);  
               this.frozenBeanDefinitionNames = null;  
           }  
           this.beanDefinitionMap.put(beanName, beanDefinition);  
           //重置所有已經註冊過的BeanDefinition的緩存  
           resetBeanDefinition(beanName);  
       }  
    }

至此,Bean定義資源文件中配置的Bean被解析過後,已經註冊到IoC容器中,被容器管理起來,真正完成了IoC容器初始化所做的全部工作。現 在IoC容器中已經建立了整個Bean的配置信息,這些BeanDefinition信息已經可以使用,並且可以被檢索,IoC容器的作用就是對這些註冊的Bean定義信息進行處理和維護。這些的註冊的Bean定義信息是IoC容器控制反轉的基礎,正是有了這些註冊的數據,容器纔可以進行依賴注入。

總結

Spring 的核心容器包括 Spring-Core、Spring-Context、Spring-beans、Spring-expression四個模塊,本文就Spring-Context中的ApplicationContext 中 FileSystemXmlApplicationContext的初始化實現進行了源碼探索,Spring-Core模塊主要就是定義了訪問資源的方式,以及對於各種資源進行用統一的接口來抽象。而Context模塊的主要作用則是爲Bean對象提供、標識一個運行時環境,初始化BeanFactory並利用BeanFactory來將解析已經註冊的Bean進而進行依賴注入,保存Bean對象之間的依賴關係。以此看來,Context的主要職責是將Core和Bean兩個模塊融合在一起。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章