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两个模块融合在一起。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值