栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Spring IOC(二):初始化

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring IOC(二):初始化

参考书籍:《Spring技术内幕》

系列文章

Spring IOC(一):概述

Spring IOC(二):初始化

Spring IOC(三):依赖注入

Spring IOC(四):相关特性

3 Spring IOC容器的初始化过程

简单来说,IoC容器的初始化是由前面介绍的refresh()方法来启动的,这个方法标志着IoC容器的正式启动。具体来说,这个启动包括BeanDefinition的Resource定位、载入和注册三个基本过程。

第一个过程是Resource定位过程。这个Resource定位指的是BeanDefinition的资源定位,它由ResourceLoader通过统一的Resource接口来完成:这个Resource对各种形式的BeanDefinition的使用都提供了统一接口。对于这些BeanDefinition的存在形式,比如,在文件系统中的Bean定义信息可以使用FileSystemResource来进行抽象,在类路径中的Bean定义信息可以使用ClassPathResource来使用,等等,这个定位过程类似于容器寻找数据的过程,就像用水桶装水先要把水找到一样。

第二个过程是BeanDefinition的载入。这个载入过程是把用户定义好的Bean表示成IoC容器内部的数据结构,而这个容器内部的数据结构就是**BeanDefinition**。具体来说,这个BeanDefinition实际上就是pojo对象在IoC容器中的抽象,通过这个BeanDefinition定义的数据结构,使IoC容器能够方便地对pojo对象也就是Bean进行管理。

第三个过程是向IoC容器注册这些BeanDefinition的过程。这个过程是通过调用
BeanDefinitionReghtiy接口的实现来完成的。这个注册过程把载入过程中解析得到的BeanDefinition向IoC容器进行注册。通过分析,我们可以看到,在IoC容器内部将BeanDefinition注入到一个HashMap中去,IoC容器就是通过这个HashMap来持有这些BeanDefinition数据的。

3.1 BeanDefinition的Resource定位

使用DefaultListablcBeanFactory时,首先定义一个Resource来定位容器要使用的BeanDefinition。这时使用的是ClassPathResource。这意味着Spring会在类路径中去寻找以文件形式存在的BeanDefinition信息。

ClassPathResource res = new ClassPathResource("spring-application.xml")

这里定义的Resource并不能由DefaultListableBeanFactory直接使用,Spring通过BeanDefinitionReader来对这些信息进行处理。

我们也可以看到使用DefaultListablcBeanFactory相对于直接使用ApplicationContext的好处。因为在Applicationcontext中,Spring已经为我们提供了一系列加载不同Resource的读取器的实现 ,而**DefaoltListableBeanFactory只是一个纯粹的IoC容器,需要为它配置特定的读取器才能完成这些功能。**当然,有利就有弊,使用DefauhListableBeanFactory这种更底层的容器,能提高定制IoC容器的灵活性。便于我们理解IOC容器。

回到我们经常使用的Applicationcontext上来,例如FileSystemXmlApplicationcontext、ClassPathXmlApplicationContext。简单地从这些类的名字上分析,可以清楚地看到它们可以提供哪些不同的Resource读入功能 , 比 如FileSystemXmlApplicationContext可以从文件系统载入Resource, ClassPathXmlApplication,Context可以从Class Path载入Resource。

下面以FileSystemXmlApplicationContext为例,通过分析这个ApplicationContext的实现来看看它是怎样完成这个Resource定位过程的。

FileSystemXmlApplicationContext的继承体系:

可以看到,这个FileSystemXmlApplicationcontext已经通过继承AbstractApplieationContext具备了ResourceLoaderi读入以Resource定义的BeanDefinition的能力,因为AbstractApplicationContext的基类是DefaultResourceLoader。下面让我们看看FileSystemXmlApplicationContext的具体实现:

public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
     
     public FileSystemXmlApplicationContext() {
     }
 
// 指定自己双亲的IOC容器
     public FileSystemXmlApplicationContext(ApplicationContext parent) {
         super(parent);
     }
 
//configLocation就是BeanDefinition所在文件的路径
     public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
         this(new String[] {configLocation}, true, null);
     }
 
     public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
         this(configLocations, true, null);
     }
 
     public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
         this(configLocations, true, parent);
     }
 
     public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
         this(configLocations, refresh, null);
     }
 
//在对象的初始化过程中,调用refresh函数载入BeanDefinition,这个refresh启动了
 
//BeanDefinition的载入过程在下面进行详细分析
     public FileSystemXmlApplicationContext(
         String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
         throws BeansException {
 
         super(parent);
         setConfigLocations(configLocations);
         if (refresh) {
             refresh();
         }
     }
 
     // 这是应用于文件系统的Resource的实现,通过构造一个fileSystemResource来得到一个文件系统定位的BeanDefinition
     @Override
     protected Resource getResourceByPath(String path) {
         if (path.startsWith("/")) {
             path = path.substring(1);
         }
         return new FileSystemResource(path);
     }
 }

在FileSystemApplicationcontext中,我们可以看到在构造函数中,实现了对configuration进行处理的功能,让所有配置在文件系统中的,以XML文件方式存在的BeanDefnition都能够得到有效的处理,比如实现了getResourceByPath方法,这个方法是一个模板方法,是为读取Resource服务的 。 对于loC容器功能的实现 ,这里没有涉及 , 因为它继承了AbstractApplicationContext 。在构造函数中通过refresh来启动IoC容器的初始化。

整个BeanDefinition资源定位的过程。这个对BeanDefinition资源定位的过程,最初是由refresh来触发的,这个refresh的调用是在FileSystemXmlBeanFactory的构造函数中启动的。然后会调用getResourceByPath()方法。

重点看看 AbstractRefreshableApplicationContext的 refreshBeanFactory 方法的实现,
这个refreshBeanFactory在FileSystemXmlApplicationContext构造函数中调用在AbstractApplicationContext中的refresh()方法中被调用。在这个方法中,通过createBeanFactroy构建了一个容器供Applicationcontext使用。这个loC容器就是我们前面提到过的DefaultListableBeanFactory,同时,它启动了loadBeanDefinitions来载人BeanDefinition,这个过程和前面来使用loC容器(XmlBeanFactory)的过程非常类似。

//FileSystemXMLApplicationContext的构造方法
 public FileSystemXmlApplicationContext(
     String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
     throws BeansException {
 
     super(parent);
     setConfigLocations(configLocations);
     if (refresh) {
         // 调用基类AbstractApplicationContext中的方法
         refresh();
     }
 }
 
 //AbstractApplicationContext的 refresh 方法
 @Override
 public void refresh() throws BeansException, IllegalStateException {
     synchronized (this.startupShutdownMonitor) {
         StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
 
         // 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);
 
         // 下面还有代码没有完全展开
     }
 }
 //
 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
     // 启动容器,并加载BeanDefinition
     refreshBeanFactory();
     return getBeanFactory();
 }
 
 //AbstractRefreshableApplicationContext中的方法
 protected final void refreshBeanFactory() throws BeansException {
     if (hasBeanFactory()) {
         destroyBeans();
         closeBeanFactory();
     }
     try {
         //构建一个IOC容器
         DefaultListableBeanFactory beanFactory = createBeanFactory();
         beanFactory.setSerializationId(getId());
         customizeBeanFactory(beanFactory);
         // 启动BeanDefinitions 来载入BeanDefinition
         loadBeanDefinitions(beanFactory);
         this.beanFactory = beanFactory;
     }
     catch (IOException ex) {
         throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
     }
 }
 
 //这就是在上下文中创建DefaultListableBeanFactory的地方
 //getInternalParentBeanFactory()会根据容器已有的双亲IOC容器信息来生成
 //DefaultLastableBeanFactory的双亲IOC容器
 protected DefaultListableBeanFactory createBeanFactory() {
     return new DefaultListableBeanFactory(getInternalParentBeanFactory());
 }
 
 //这里使用BeanDefinitionReader载入Bean定义的地方,允许有多种载入方式,
 //这里通过一个抽象函数把具体的实现委托给子类来完成
 protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
     throws BeansException, IOException;
 
 //我们看一下在AbstractApplicationContext中对这个方法的重写,这个类的重写从名称就可以看出来是载入XML文件得BeanDefinition
 @Override
 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
     // Create a new XmlBeanDefinitionReader for the given BeanFactory.
     // 创建一个Xml的BeanDefinition的阅读器
     XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
 
     // Configure the bean definition reader with this context's
     // resource loading environment.
     beanDefinitionReader.setEnvironment(this.getEnvironment());
     beanDefinitionReader.setResourceLoader(this);
     beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
 
     // Allow a subclass to provide custom initialization of the reader,
     // then proceed with actually loading the bean definitions.
     // 允许初始化Reader
     initBeanDefinitionReader(beanDefinitionReader);
     //使用BeanDefinitionReader加载BeanDefinitions
     loadBeanDefinitions(beanDefinitionReader);
 }
 //AbstractXmlApplicationContext类中的该方法,加载BeanDefinition,在加载之前肯定要找到BeanDefinition的Resource定位
 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
     //以Resource的方式获得配置文件的资源位置
     Resource[] configResources = getConfigResources();
     if (configResources != null) {
         reader.loadBeanDefinitions(configResources);
     }
     // 以String的方式获取配置文件的位置
     String[] configLocations = getConfigLocations();
     if (configLocations != null) {
         //查找到Resource之后,加载BeanDefinition
         reader.loadBeanDefinitions(configLocations);
     }
 }
 
 // 这个方法就是加载Resource,在AbstractBeanDefinitionReader类中
 public int loadBeanDefinitions(String location, @Nullable Set actualResources) throws BeanDefinitionStoreException {
     // 获取ResourceLoader 这里使用的是DefaultResourceLoader
     ResourceLoader resourceLoader = getResourceLoader();
     if (resourceLoader == null) {
         throw new BeanDefinitionStoreException(
             "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
     }
     //这里对Resource的路径模式进行解析,比如我们设定的各种Ant格式的路径定义,得到需要的Resource集合
     //这些Resource集合指向我们已经定义好的BeanDefinition信息,可以是多个文件
     if (resourceLoader instanceof ResourcePatternResolver) {
         // Resource pattern matching available.
         try {
             //调用 DefaultResourceLoader 的 getRe source 完成具体的 Resource 定位
             Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
             int count = loadBeanDefinitions(resources);
             if (actualResources != null) {
                 Collections.addAll(actualResources, resources);
             }
             if (logger.isTraceEnabled()) {
                 logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
             }
             return count;
         }
         catch (IOException ex) {
             throw new BeanDefinitionStoreException(
                 "Could not resolve bean definition resource pattern [" + location + "]", ex);
         }
     }
     else {
         // Can only load single resources by absolute URL.
         // 通过绝对的URL路径加载
         Resource resource = resourceLoader.getResource(location);
         int count = loadBeanDefinitions(resource);
         if (actualResources != null) {
             actualResources.add(resource);
         }
         if (logger.isTraceEnabled()) {
             logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
         }
         return count;
     }
 }
 
 //看一下如何查找一个resource,通过DefaultResourceLoader类得到一个Resource定位,
 public Resource getResource(String location) {
     Assert.notNull(location, "Location must not be null");
 
     for (ProtocolResolver protocolResolver : getProtocolResolvers()) {
         Resource resource = protocolResolver.resolve(location, this);
         if (resource != null) {
             return resource;
         }
     }
     //使用子类自己实现的方式定位到resource
     if (location.startsWith("/")) {
         return getResourceByPath(location);
     }
     //处理classpath标识的resource
     else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
         return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
     }
     else {
         try {
             // Try to parse the location as a URL...
             URL url = new URL(location);
             return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
         }
         catch (MalformedURLException ex) {
             // No URL -> resolve as resource path.
             // 使用子类实现的方式找到resource
             return getResourceByPath(location);
         }
     }
 }

getResourceByPath会被子类FileSystemXmlApplicationContext实现,这个方法返回的是一个FileSystemResource对象,通过这个对象,Spring可以进行相关的I/O操作,完成BeanDefinition的定位。分析到这里已经一目了然,它实现的就是对path进行解析,然后生成一个FileSystemResource对象并返回,

@Override
 protected Resource getResourceByPath(String path) {
     if (path.startsWith("/")) {
         path = path.substring(1);
     }
     return new FileSystemResource(path);
 }

如果是其他的ApplicationContext,那么会对应生成其他种类的Resource,比如ClassPathResource、ServletContextResource等。 关于Spring中Resource的种类,可以在Resource类的继承关系中了解。作为接口的Resource定义了许多与I/O相关的操作,这些操作也都可以从Resource的接口定义中看到。这些接口对不同的Resource实现代表着不同的意义,是Resource的实现需要考虑的。Resource接 口的实现在Spring中的设计下所示:

总结: 通过对前面的实现原理的分析,我们以FileSystemXmlApplicationcontext的实现原理为例子,了解了Resource定位问题的解决方案,即以FileSystem方式存在的Resource的定位实现。

回顾一下流程: 首先我们看到FileSystemXMLApplicationContext的构造函数中调用refresh()方法,容器的初始化过程由此开始,refresh()方法是基类AbstractApplicationContext中的方法,在该方法中,又调用AbstractRefreshableApplicationContext中的方法refreshBeanFactory()方法,在此方法中,创建了DefaultListableBeanFactoryIOC的默认容器并开始加载BeanDefinition。首先通过AbstractBeanDefinitionReader类中的loadBeanDefinitions()方法加载到所有的Resource,是通过DefaultResourceLoader结构存储。然后看一下如何查找到一个Resource的定位的,通过DefaultResourceLoader中定义的方法查找到一个Resource定位,会从通过classPath查找,通过URL绝对路径查找,通过子类实现的getResourceByPath()方法查找。以上就是启动一个容器并找到Resource定位。

在BeanDefinition定位完成的基础上,就可以通过返回的Resource对象来进行BeanDefinition的载入了。在定位过程完成以后,为BeanDefinition的载入创造了I/O操作的条件,但是具体的数据还没有开始读入。这些数据的读入将在下面介绍的BeanDefinition的载入和解析中来完成。仍然以水桶为例子,这里就像用水桶去打水,要先找到水源。这里完成对Resource的定位,就类似于水源已经找到了,下面就是打永的过程了,类似子把找到的水装到水桶里的过程。找水不简单,但是与打水相比,我们发现打水更需要技巧。

3.2 BeanDefinition的载入和解析

在完成对代表BeanDefinition的Resource定位的分析后,下面来了解整个BeanDefinition信息的载入过程。对loC容器来说,这个载入过程,相当于把定义的BeanDefinition在IoC容器中转化成一个Spring内部表示的数据结构(这个数据结构就是BeanDefinition)的过程。**loC容器对Bean的管理和依赖注入功能的实现,是通过对其持有的BeanDefinition进行各种相关操作来完成的。**这些BeanDefinition数据在IoC容器中通过一个ConcurrentHashMap来保持和维护。当然这只是-种比较简单的维护方式,如果需要提髙IoC容器的性能和容量,完全可以自己做一些扩展。

从 DefaultListableBeanFactory的设计入手,看看IoC容器是怎样完成BeanDefinition载入的。这个DefaultListableBeanFactory就是IOC默认的容器,其内部实现类容器的基本功能。它相比于ApplicationContext容器比较底层,ApplicationContext是更高形态的容器,它只是一个对Bean操作的结构,而ApplicationContext包括了它并且增加了很多功能,比如Resource定位,事件等等。

再次来看一下IoC容器的初始化人口,也就是看一下refresh()方法。这个方法的最初是在FileSystemXmlApplicationContext的构造函数中被调用的,它的调用标志着容器初始化的开始,这些初始化对象就是BeanDefinition数据,初始化人口(以FileSystemXMLApplicationContext为例):

public FileSystemXmlApplicationContext(
     String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
     throws BeansException {
 
     super(parent);
     setConfigLocations(configLocations);
     //启动容器,开始初始化
     if (refresh) {
         refresh();
     }
 }

对容器的启动来说,refresh()是一个很重要的方法,下面介绍一下它的实现该方法在AbstractApplicationContext类 (它是FileSystemXmlApplicationContext的基类) 中找到,它详细的描述了整个ApplicationContext的初始化过程,比如BeanFactory的更新MessageSource和PostProcessor的注册等等。这里看起来更像是对ApplicationContext进行初始化的模板或执行提纲,这个执行过程为Bean的生命周期管理提供了条件。

//AbstractApplicationContext类中
 @Override
 public void refresh() throws BeansException, IllegalStateException {
     synchronized (this.startupShutdownMonitor) {
         StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
 
         // 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.
             // 设置BeanFactory的后置处理器
             postProcessBeanFactory(beanFactory);
 
             StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
             // Invoke factory processors registered as beans in the context.
             //调用BeanFactory的后处理器,这些后处理器是在Bean定义中向容器注册的
             invokeBeanFactoryPostProcessors(beanFactory);
 
             // Register bean processors that intercept bean creation.
             //注册Bean的后处理器,在Bean创建过程中调用
             registerBeanPostProcessors(beanFactory);
             beanPostProcess.end();
 
             // Initialize message source for this context.
             //对上下文中的消息源进行初始化
             initMessageSource();
 
             // Initialize event multicaster for this context.
             //初始化上下文中的事件机制
             initApplicationEventMulticaster();
 
             // Initialize other special beans in specific context subclasses.
             //初始化其他的特殊Bean
             onRefresh();
 
             // Check for listener beans and register them.
             //检查监听Bean并且将这些Bean向容器注册
             registerListeners();
 
             // Instantiate all remaining (non-lazy-init) singletons.
             //实例化所有的(non-lazy-init)单例
             finishBeanFactoryInitialization(beanFactory);
 
             // Last step: publish corresponding event.
             //发布容器事件.结束Refresh过程
             finishRefresh();
         }
 
         catch (BeansException ex) {
             if (logger.isWarnEnabled()) {
                 logger.warn("Exception encountered during context initialization - " +
                             "cancelling refresh attempt: " + ex);
             }
 
             // Destroy already created singletons to avoid dangling resources.
             //为防止Bean资源占用,在异常处理中,销毁巳经在前面过程中生成的单例Bean
             destroyBeans();
 
             // Reset 'active' flag.
             //重置"active"标志
             cancelRefresh(ex);
 
             // Propagate exception to caller.
             throw ex;
         }
 
         finally {
             // Reset common introspection caches in Spring's core, since we
             // might not ever need metadata for singleton beans anymore...
             resetCommonCaches();
             contextRefresh.end();
         }
     }
 }

进人到AbstractRefreshableApplicationContext的refreshBeanFaetory()方法中,在这个方法中创建了BeanFactory。在创建loC容器前,如果已经有容器存在,那么需要把已有的容器销毁和关闭,保证在refresh以后使用的是新建立起来的loC容器。这么看来,这个refresh非常像重启动容器。在建立好当前的loC容器以后,开始了对容器的初始化过程,比如BeanDefinition的载人。具体流程看下图:

//AbstractRefreshableApplicationContext类中:
 @Override
 protected final void refreshBeanFactory() throws BeansException {
     if (hasBeanFactory()) {
         destroyBeans();
         closeBeanFactory();
     }
     try {
         //构建一个IOC容器
         DefaultListableBeanFactory beanFactory = createBeanFactory();
         beanFactory.setSerializationId(getId());
         customizeBeanFactory(beanFactory);
         // 启动BeanDefinition 来载入BeanDefinition
         loadBeanDefinitions(beanFactory);
         this.beanFactory = beanFactory;
     }
     catch (IOException ex) {
         throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
     }
 }

BeanDefinition载入的交互过程:

这里调用的loadBeanDefinitions实际上是一个抽象方法,那么实际的载入过程发生在哪里呢?我们看看前面提到的loadBeanDefinilions在AbstractRefreshableAppneationContext的子类AbstractXmlApplicationcontext中的实现,在这个loadBeanDefinitions中,初始化了读取器
XmlBeanDefinitionReader,然后把这个读取器在IoC容器中设置好,最后是启动读取器来完成BeanDefinition在IoC容器中的载入。

//AstractXmlApplicationContext中对loadBeanDefinitions方法的实现
 @Override
 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
     // Create a new XmlBeanDefinitionReader for the given BeanFactory.
     // 创建一个Xml的BeanDefinition的阅读器,并通过回调设置到BeanFactory中去。
     XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
 
     // Configure the bean definition reader with this context's
     // resource loading environment.
     beanDefinitionReader.setEnvironment(this.getEnvironment());
     //为XMLBeanDefinitionReader配ResourceLoader,因为DefaultResourceLoader是父类,所以this可以直接使用
     beanDefinitionReader.setResourceLoader(this);
     beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
 
     // Allow a subclass to provide custom initialization of the reader,
     // then proceed with actually loading the bean definitions.
     // 下面是启动Bean定义信息载入的过程
     // 允许初始化Reader
     initBeanDefinitionReader(beanDefinitionReader);
     //使用BeanDefinitionReader加载BeanDefinitions
     loadBeanDefinitions(beanDefinitionReader);
 }

接着就是loadBeanDefinitions调用的地方,首先得到BeanDefinition信息的Resource定位,然后直接调用XMLBeanDefinitionReader来读取,具体的载人过程是委托给BeanDefinitionReader完成的。因为这里的BeanDefinition是通过XML文件定义的,所以这里使用XmlBeanDefinitionReader来载入BeanDefinition到容器中。

//XmlBeanDefinitionReader来载入BeanDefinition到容器中。
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    //以Resource的方式获得配置文件的资源位置
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
        reader.loadBeanDefinitions(configResources);
    }
    // 以String的方式获取配置文件的位置
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        reader.loadBeanDefinitions(configLocations);
    }
}

通过以上对实现原理的分析,我们可以看到,在初始化FileSystmXmlApplicationContext的过程中是通过调用IoC容器的refresh()来启动整个BeanDefinition的载入过程的,这个初始化是通过定义的XmlBeanDefinitionReader来完成的。同时,我们也知道实际使用的IoC容器是DefultListableBeanFactory,具体的Resource载入在XmlBeanDefinitionReader读入BeanDefinition时实现。因为Spring可以对应不同形式的BeanDefinition。由于这里使用的是XML方式的定义,所以需要使用XmlBeanDefinitionReader,如果使用了其他的BeanDefinition方式,就需要使用其他种类的BeanDefinitionReader来完成数据的载入工作。

在XmlBeanDefimtionReader的实现中可以看到,是在reader.loadBeanDefinitions()中开始进行
BeanDefinition的载人的,而这时XmlBeanDefinitionReader的父类AbstractBeanDefinitionReader已经为BeanDefinition的载入做好了准备。

@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
    // 如果Resource为空,则停止BeanDefinition的载入
    // 然后启动载入BeanDefinition的过程,这个过程会遍历整个Resource集合所包含的BeanDefinition信息
    Assert.notNull(resources, "Resource array must not be null");
    int count = 0;
    for (Resource resource : resources) {
        count += loadBeanDefinitions(resource);
    }
    return count;
}

这里调用的是loadBeanDefinitions(Resource res)方法,但这个方法在AbstractBeanDefinitionReader类里是没有实现的,它是一个接口方法,具体的实现在XmlBeanDefinitionReader 中,在读取器中,需要得到代表XML文件的Resource,因为这个Resource对象封装了对XML文件的I/O操作,所以读取器可以在打开IO流后得到XML的文件对象。有了这个文件对象以后,就可以按照Spring的Bean定义规则来对这个XML的文档树进行解析了,这个解析是交给BeanDefinitionParserDelegate来完成的,看起来实现脉络很清楚具体可以参考代码实现:

//这个载入BeanDefinition的方法在AbstractBeanDefinitionReader类里没有实现,它是一个BeanDefinitionReader接口定义的一个方法,由各种加载BeanDefinition的子类实现,我们这里分析的是FileSystemXMLApplicationContext容器,加载的是XML文件,所以使用的是XMLBeanDefinitionReader加载BeanDefinition的Resource定位
int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;

//下面看XMLBeanDefinitionReader类中对这个方法的实现
// 调用入口
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    return loadBeanDefinitions(new EncodedResource(resource));
}
// 在此类中继续
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isTraceEnabled()) {
        logger.trace("Loading XML bean definitions from " + encodedResource);
    }

    Set currentResources = this.resourcesCurrentlyBeingLoaded.get();

    if (!currentResources.add(encodedResource)) {
        throw new BeanDefinitionStoreException(
            "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    //这里得到Xml文件,并得到IO的InputSource准备进行读取
    try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
        InputSource inputSource = new InputSource(inputStream);
        if (encodedResource.getEncoding() != null) {
            inputSource.setEncoding(encodedResource.getEncoding());
        }
        //具体的读取操作
        return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(
            "IOException parsing XML document from " + encodedResource.getResource(), ex);
    }
    finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}

// 接着看具体的读取定义bean的xml文件
// 具体的读取过程,这是从特定的XML文件中实际载入BeanDefinition的地方
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
    throws BeanDefinitionStoreException {

    try {
        // 这里取得XML文件的document对象,这个解析过程是由documentLoader完成的这个documentLoader
        // 是DefaultdocumentLoader,在定义documentLoader的地方创建
        document doc = doLoaddocument(inputSource, resource);
        //这里启动的是对BeanDefinition解析的详细过程,这个解析会使用到Spring的Bean配置规则。
        int count = registerBeanDefinitions(doc, resource);
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + count + " bean definitions from " + resource);
        }
        return count;
    }
    catch (BeanDefinitionStoreException ex) {
        throw ex;
    }
    catch (SAXParseException ex) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                                                  "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
    }
    catch (SAXException ex) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                                                  "XML document from " + resource + " is invalid", ex);
    }
    catch (ParserConfigurationException ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                                               "Parser configuration exception parsing XML from " + resource, ex);
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                                               "IOException parsing XML document from " + resource, ex);
    }
    catch (Throwable ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                                               "Unexpected exception parsing XML document from " + resource, ex);
    }
}

接着说,Spring的BeanDefinion是怎样按照Spring的Bean语义要求进行解析并转化为容器内部数据结构的,这个过程是在registerBeanDefinitions(doc,resource)中完成的。具体的过程是由BeanDefinitiondocumentReader来完成的,这个registerBeanDefinition还对载入的Bean的数量进行了统计。

// 在XMLBeanDefinitionReader中的方法:
public int registerBeanDefinitions(document doc, Resource resource) throws BeanDefinitionStoreException {
    // 这里得到BeanDefinitiondocumentReader来对XML中的bean的定义进行解析
    BeanDefinitiondocumentReader documentReader = createBeanDefinitiondocumentReader();
    int countBefore = getRegistry().getBeanDefinitionCount();
    // 具体的解析过程在这个registerBeanDefinitions 完成
    documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    return getRegistry().getBeanDefinitionCount() - countBefore;
}

BeanDefinition的载入分成两部分,首先通过调用XML的解析器得到document对象,但这些document对象并没有按照Spring的Bean规则进行解析。在完成通用的XML解析以后,才是按照Spring的Bean规则进行解析的地方,这个按照Spring的Bean规则进行解析的过程是在documentReader中实现的。这里使用的documentReader是默认设置好的DefaultBeanDefinitiondocumentReader。这个DefaultBeanDefinitiondocumentReader的创建是在后面的方法中完成的,然后再完成BeanDefinition的处理, 处理的结果由BeanDefinitionHolder对象来持有。这个BeanDefinitionHolder除了持有BeanDefinition对象外,还持有其他与BeanDefinition的使用相关的信息,比如Bean的名字、别名集合等。这个BeanDefinitionHolder的生成是通过对document文档树的内容进行解析来完成的,可以看到这个解析过程是由DefaultBeanDefinitiondocumentReader类来实现(具体在processBeanDefinition方法中实现)的,同时这个解析是与Spring对BeanDefinition的配置规则紧密相关的。具体的实现原理看如下代码:

// 在XMLBeanDefinitionReader中的方法:
//获取到documentReader以后,为具体的Spring Bean的解析过程准备好了数据
protected BeanDefinitiondocumentReader createBeanDefinitiondocumentReader() {
    return BeanUtils.instantiateClass(this.documentReaderClass);
}

//DefaultBeanDefinitiondocumentReader类中:
// 这里是处理BeanDefinition的地方,具体的处理委托给 BeanDefinitionParserDelegate类来完成
// root对应在Spring BeanDefinition中定义的XML元素
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // BeanDefinitionHolder是BeanDefinition对象的封装类,封装了BeanDefinition,Bean的名字和别名,
    // 用它来完成向IOC容器的注册,得到这个BeanDefinitionHolder 就意味着BeanDefinition是通过BeanDefinitionParserDelegate对
    // XML元素的信息按照Spring的Bean规则进行解析得到的
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // Register the final decorated instance.
            // 这里是向IOC容器注册解析得到的BeanDefinition的地方
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to register bean definition with name '" +
                                     bdHolder.getBeanName() + "'", ele, ex);
        }
        // Send registration event.
        // 在BeanDefinition向IOC容器注册完以后,发送消息
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}

具体的Spring BeanDefinition的解析是在BeanDefinitionParserDelegate中完成的。这个类里包含了对各种Spring Bean定义规则的处理。比如我们最熟悉的对Bean元素的处理是怎样完成的,也就是怎样处理在XML定义文件中出现的这个最常见的元素信息。在这里会看到对那些熟悉的BeanDefinition定义的处
理,比如id、name、aliase等 属性元素。把这些元素的值从XML文件相应的元素的属性中读取出来以后,设置到生成的BeanDefinitionHolder中去。这些属性的解析还是比较简单的。对于其他元素配置的解析,比如各种Bean的属性配置,通过一个较为复杂的解析过程,这个过程是由parseBeanDefinitionElement来完成的。解析完成以后,会把解析结果放到BeanDefinition对象中并设置到BeanDefinitionHolder中去,如下面代码所示:

//BeanDefinitionParserDelegate类中:
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
    这里取得在元素中定义的id, name和aliase属性的值 
    String id = ele.getAttribute(ID_ATTRIBUTE);
    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

    List aliases = new ArrayList<>();
    if (StringUtils.hasLength(nameAttr)) {
        String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
        aliases.addAll(Arrays.asList(nameArr));
    }

    String beanName = id;
    if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
        beanName = aliases.remove(0);
        if (logger.isTraceEnabled()) {
            logger.trace("No XML 'id' specified - using '" + beanName +
                         "' as bean name and " + aliases + " as aliases");
        }
    }

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

    return null;
}

上面介绍了对Bean元素进行解析的过程,也就是BeanDefinition依据XML的 的定义被创建的过程。这个**BeanDefinition可以看成是对<bean>定义的抽象**。

这个数据对象中封装的数据大多都是与<bean>< /bean >定义相关的,也有很多就是我们在定义Bean时看到
的那些Spring标记,比如常见的init-method、destroy-method, factory-method,等等,这个
BeanDefinition数据类型最非常重要的,它封装了很多基本数据,这些基本数据都是IoC容器需要的。有了这些基本数据,IoC容器才能对Bean配置进行处理,才能实现相应的容器特性。

**这个BeanDefinition是IoC容器体系中非常重要的核心数据结构。**通过解析以后,这些数据已经做好在IoC容器里大显身手的准备了。

下面看一下,如何生成BeanDefinition的:

@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
    Element ele, String beanName, @Nullable BeanDefinition containingBean) {

    this.parseState.push(new BeanEntry(beanName));
    //这里只读取定义的中设置的class名字,然后带入到BeanDefinition中去,只是做个记录,并不
    // 涉及对象的实例化过程,对象的实例化实际上是在依赖注入时完成的
    String className = null;
    if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
        className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
    }
    String parent = null;
    if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
        parent = ele.getAttribute(PARENT_ATTRIBUTE);
    }

    try {
        // 这里生成需要的BeanDefinition对象,为Bean定义信息的载入做准备
        AbstractBeanDefinition bd = createBeanDefinition(className, parent);
        // 这里对当前的Bean元素进行属性解析,并设置description的信息
        parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
        bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DEscriptION_ELEMENT));
        //从名字可以清楚地看到,这里是对各种元素的信息进行解析的地方
        parsemetaElements(ele, bd);
        parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
        parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
        // 解析的构造函数设置
        parseConstructorArgElements(ele, bd);
        // 解析的property设置
        parsePropertyElements(ele, bd);
        parseQualifierElements(ele, bd);

        bd.setResource(this.readerContext.getResource());
        bd.setSource(extractSource(ele));

        return bd;
    }
    //这些异常是在配置Bean出现问题时经常会看到的
    catch (ClassNotFoundException ex) {
        error("Bean class [" + className + "] not found", ele, ex);
    }
    catch (NoClassDefFoundError err) {
        error("Class that bean class [" + className + "] depends on not found", ele, err);
    }
    catch (Throwable ex) {
        error("Unexpected failure during bean definition parsing", ele, ex);
    }
    finally {
        this.parseState.pop();
    }

    return null;
}

上面是具体生成BeanDefinition的地方。在这里,我们举一个对property进行解析的例子来完成对整个BeanDefinition载人过程的分析,还是在类BeanDefinitionParserDelegate的代码中,一层一层地对BeanDefinition中的定义进行解析,比如从属性元素集合到具体的毎一个属性元素,然后才是对具体的属性值的处理。根据解析结果,对这些属性值的处理会被封装成Property Value对象并设置到BeanDefinition对象中去。

//BeanDefinitionParserDelegate类中:
//这里对指定Bean元素的property子元素集合进行解析
public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
    //遍历Bean元素下定义的所有property元素
    NodeList nl = beanEle.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
            // 在判断是property元素后对该property元素进行解析的过程
            parsePropertyElement((Element) node, bd);
        }
    }
}
//对单个的属性解析,解析出值之后,放入到beanDefinition中去
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的地方,返回的对象对应对Bean定义的property属性设置解析结果,
        //这个解析结果回封装到propertyValue对象中,然后设置到beanDefinition中去
        Object val = parsePropertyValue(ele, bd, propertyName);
        PropertyValue pv = new PropertyValue(propertyName, val);
        parsemetaElements(ele, pv);
        pv.setSource(extractSource(ele));
        bd.getPropertyValues().addPropertyValue(pv);
    }
    finally {
        this.parseState.pop();
    }
}

// 这里获取一个Property元素的值
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
    String elementName = (propertyName != null ?
                          " element for property '" + propertyName + "'" :
                          " element");

    // Should only have one child element: ref, value, list, etc.
    NodeList nl = ele.getChildNodes();
    Element subElement = null;
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element && !nodeNameEquals(node, DEscriptION_ELEMENT) &&
            !nodeNameEquals(node, meta_ELEMENT)) {
            // Child element is what we're looking for.
            if (subElement != null) {
                error(elementName + " must not contain more than one sub-element", ele);
            }
            else {
                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.setSource(extractSource(ele));
        return ref;
    }
    // 如果是value,创建爱你一个value的数据对象TypedStringValue,这个对象封装了value的信息
    else if (hasValueAttribute) {
        TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
        valueHolder.setSource(extractSource(ele));
        return valueHolder;
    }
    //如果还有子元素,触发对子元素的解析
    else if (subElement != null) {
        return parsePropertySubElement(subElement, bd);
    }
    else {
        // Neither child element nor "ref" or "value" attribute found.
        error(elementName + " must specify a ref or value", ele);
        return null;
    }
}

这里是对property子元素的解析过程,Array、List. Set. Map、Prop等各种元素都会在这里进行解析,生成对应的数据对象,比如ManagedList, ManagedArray、ManagedSet等。这些Managed类是Spring对具体的BeanDefinition的数据封装。,比如 parseArrayElement, parseListElement, parseSetElement parseMapElement. parsePropEIement对应着不同类型的数据解析,同时这些具体的解析方法
在BeanDefinitionParserDelegate类中也都能够找到。因为方法命名很清晰,所以从方法名字上就能够很快地找到。下面以对Property的元素进行解析的过程为例,通过它的实现来说明具体的解析过程是怎样完成的:

XML 的定义:


    
    
        
            administrator@example.org
            support@example.org
            development@example.org
        
    
    
    
        
            a list element followed by a reference
            
        
    
    
    
        
            
            
        
    
    
    
        
            just some string
            
        
    

对一个Property中的子元素解析

// 对property中的子元素进行解析,比如list,map,prop等
public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable String defaultValueType) {
    if (!isDefaultNamespace(ele)) {
        return parseNestedCustomElement(ele, bd);
    }
    else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
        BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
        if (nestedBd != null) {
            nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
        }
        return nestedBd;
    }
    else if (nodeNameEquals(ele, REF_ELEMENT)) {
        // A generic reference to any name of any bean.
        String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
        boolean toParent = false;
        if (!StringUtils.hasLength(refName)) {
            // A reference to the id of another bean in a parent context.
            refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
            toParent = true;
            if (!StringUtils.hasLength(refName)) {
                error("'bean' or 'parent' is required for  element", ele);
                return null;
            }
        }
        if (!StringUtils.hasText(refName)) {
            error(" element contains empty target attribute", ele);
            return null;
        }
        RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
        ref.setSource(extractSource(ele));
        return ref;
    }
    else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
        return parseIdRefElement(ele);
    }
    else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
        return parsevalueElement(ele, defaultValueType);
    }
    else if (nodeNameEquals(ele, NULL_ELEMENT)) {
        // It's a distinguished null value. Let's wrap it in a TypedStringValue
        // object in order to preserve the source location.
        TypedStringValue nullHolder = new TypedStringValue(null);
        nullHolder.setSource(extractSource(ele));
        return nullHolder;
    }
    else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
        return parseArrayElement(ele, bd);
    }
    //子元素是List
    else if (nodeNameEquals(ele, LIST_ELEMENT)) {
        return parseListElement(ele, bd);
    }
    else if (nodeNameEquals(ele, SET_ELEMENT)) {
        return parseSetElement(ele, bd);
    }
    else if (nodeNameEquals(ele, MAP_ELEMENT)) {
        return parseMapElement(ele, bd);
    }
    else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
        return parsePropsElement(ele);
    }
    else {
        error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
        return null;
    }
}

下面看看List这样的属性配置是怎样被解析的,依然是在BeanDefinitionParserDelegate中:返回的是一个List对象,这个List是Spring定义的ManagedList,作为封装List这类配置定义的数据封装,如下代码:

public List parseListElement(Element collectionEle, @Nullable BeanDefinition bd) {
    String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
    NodeList nl = collectionEle.getChildNodes();
    ManagedList target = new ManagedList<>(nl.getLength());
    target.setSource(extractSource(collectionEle));
    target.setElementTypeName(defaultElementType);
    target.setMergeEnabled(parseMergeAttribute(collectionEle));
    // 具体的List元素解析过程
    parseCollectionElements(nl, target, bd, defaultElementType);
    return target;
}

protected void parseCollectionElements(
    NodeList elementNodes, Collection target, @Nullable BeanDefinition bd, String defaultElementType) {
    //遍历所有的元素节点,并判断其类型是否是Element
    for (int i = 0; i < elementNodes.getLength(); i++) {
        Node node = elementNodes.item(i);
        if (node instanceof Element && !nodeNameEquals(node, DEscriptION_ELEMENT)) {
            //加入到target中,target是一个个ManagedList,同时触发下一层子元素的解析过程,递归调用
            target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
        }
    }
}
 

经过这样逐层地解析,我们在XML文件中定义的BeanDefinition就被整个裁入到了IoC容器中,并在容器中建立了数据映射。在IOC容器中建立了对应的数据结构,或者说可以看成是POJO对象在IoC容器中的抽象,这些数据结构可以以AbstractBeanDefinition为人口,让IoC容器执行索引、査询和操作。简单的POJO操作背后其实蕴含着一个复杂的抽象过程,经过以上的载入过程,IOC容器大致完成了管理Bean对象的数据准备工作(或者说是初始化过程)。但是,重要的依赖注入实际上在这个时候还没有发生,现在,在IOC容器BeanDefinition中存在的还只是一些静态的配置信息。严格地说,这时候的容器还没有完全起作用,要完全发挥容器的作用,还需完成数据向容器的注册。

3.3 BeanDefinition在IOC容器中的注册

前面已经分析过BeanDefinition在IoC容器中载人和解析的过程。在这些动作完成以后,用户定义的BeanDefinition信息已经在loC容器内建立起了自己的数据结构以及相应的数据表示,但此时这些数据还不能供IoC容器直接使用,需要在IoC容器中对这些BeanDefinition数据进行注册。这个注册为IoC容器提供了更友好的使用方式,在DefaultListableBeanFactory中,是通过一个HashMap来持有载入的BeanDefinition的,这个HashMap的定义在DefaultListableBeanFactory中可以看到,如下所示:

private final Map beanDefinitionMap = new ConcurrentHashMap<>(256);

将解析得到的BeanDefinition向IOC容器中的beanDefinitionMap注册的过程是在载入BeanDefinition完成后进行的,如下代码所示:

可以看到在解析完成之后,随即开始注册。

//DefaultBeanDefinitiondocumentReader类中:
// 这里是处理BeanDefinition的地方,具体的处理委托给 BeanDefinitionParserDelegate类来完成
// root对应在Spring BeanDefinition中定义的XML元素,处理完BeanDefinition之后,随即向容器中注册,这里调用的是BeanDefinitionReaderUtils中的方法。最终实现注册逻辑的是DefaultListableBeanFactory中的registerBeanDefinition()方法
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // BeanDefinitionHolder是BeanDefinition对象的封装类,封装了BeanDefinition,Bean的名字和别名,
    // 用它来完成向IOC容器的注册,得到这个BeanDefinitionHolder 就意味着BeanDefinition是通过BeanDefinitionParserDelegate对
    // XML元素的信息按照Spring的Bean规则进行解析得到的
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // Register the final decorated instance.
            // 这里是向IOC容器注册解析得到的BeanDefinition的地方
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to register bean definition with name '" +
                                     bdHolder.getBeanName() + "'", ele, ex);
        }
        // Send registration event.
        // 在BeanDefinition向IOC容器注册完以后,发送消息
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}

我们跟踪以上的代码调用去看一下具体的注册实现,在DefaultListableBeanFactory中实现了BeanDefinitionRegistry的接口,这个接口的实现完成BeanDefinition向容器的注册。这个注册过程不复杂,就是把解析得到的BeanDefinition设置到hashMap中去。需要注意的是,如果遇到同名的BeanDefinition,进行处理的时候需要依据allowBeanDefinitionOverriding的配置来完成。具体的实现如代码:

//在DefaultListableBeanFactory类中BeanDefinition注册实现:
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
    throws BeanDefinitionStoreException {

    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");

    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition) beanDefinition).validate();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                                                   "Validation of bean definition failed", ex);
        }
    }
    //这里检查是否有相同名字的BeanDefinition已经在IOC容器中注册了,如果有相同名字的BeanDefinition,但是不允许覆盖,那么会抛出异常
    BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
    if (existingDefinition != null) {
        if (!isAllowBeanDefinitionOverriding()) {
            throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
        }
        else if (existingDefinition.getRole() < beanDefinition.getRole()) {
            // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
            if (logger.isInfoEnabled()) {
                logger.info("Overriding user-defined bean definition for bean '" + beanName +
                            "' with a framework-generated bean definition: replacing [" +
                            existingDefinition + "] with [" + beanDefinition + "]");
            }
        }
        else if (!beanDefinition.equals(existingDefinition)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Overriding bean definition for bean '" + beanName +
                             "' with a different definition: replacing [" + existingDefinition +
                             "] with [" + beanDefinition + "]");
            }
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("Overriding bean definition for bean '" + beanName +
                             "' with an equivalent definition: replacing [" + existingDefinition +
                             "] with [" + beanDefinition + "]");
            }
        }
        this.beanDefinitionMap.put(beanName, beanDefinition);
    }
    else {
        if (hasBeanCreationStarted()) {
            // Cannot modify startup-time collection elements anymore (for stable iteration)
            synchronized (this.beanDefinitionMap) {
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                removeManualSingletonName(beanName);
            }
        }
        // 这是正常注册BeanDefinition的过程,把Bean的名字存入到BeanDefinitionNames的同时,
        // 把beanName作为Map的key,把beanDefinition做为value存入到IOC容器持有的beanDefinitionMap中
        else {
            // Still in startup registration phase
            this.beanDefinitionMap.put(beanName, beanDefinition);
            this.beanDefinitionNames.add(beanName);
            removeManualSingletonName(beanName);
        }
        this.frozenBeanDefinitionNames = null;
    }

    if (existingDefinition != null || containsSingleton(beanName)) {
        resetBeanDefinition(beanName);
    }
    else if (isConfigurationFrozen()) {
        clearByTypeCache();
    }
}

完成了BeanDefinition的注册,就完成了loC容器的初始化过程。此时,在使用的IoC容器DefaultListableBeanFactory中已经建立了整个Bean的配置信息,而且这些BeanDefinition已经可以被容器使用了,它们都在beanDefinitionMap里被检索和使用。容器的作用就是对这些信息进行处理和维护。这些信息是容器建立依赖反转的基础,有了这些基础数据,下面我们看一下在IoC容器中,依赖注入是怎样完成的。

3.4 初始化总结

**总结:**首先还是在FileSystemXMLApplicationContext中refresh()方法开始,这个方法的具体实现是在AbstractApplicationContext中,在refresh()方法中,首先让子类AbstractRefreshableApplicationContext中refreshBeanFactory()方法中创建DefaultListableBeanFactory容器他是一个IOC默认的容器,然后在这个方法中继续执行,调用loadBeanDefinitions()去加载BeanDefinition,这个方法是一个接口方法,具体的实现类由BeanDefinition的来源不同而不同,如果是加载的xml文件,那么由XMLBeanDefinitionReader去加载BeanDefinition。加载BeanDefinition那么需要先定位到Resource,通过AbstractBeanDefinitionReader类中的loadBeanDefinitions()方法加载到所有的Resource,是通过DefaultResourceLoader结构存储。找到Resource定位之后,就开始加载BeanDefinition,通过Resource可以用IO操作XmL,首先将XML解析为document文档树,然后在由documentReader根据SpringBean的规则进行解析,具体解析操作由BeanDefinitionParserDelegate类中的方法进行解析,这个类中有很多解析方法,包括对Property的子元素等等。解析完成之后返回一个BeanDefinitionHolder,这个结构包括所有的解析完成的BeanDefinition,至此解析过程就完成了。随机开始进行注册操作,注册操作比较简单,主要过程由DefaultListableBeanFactory来完成。

3.5 初始化之后的工作

从下面代码中可以看到,在完成容器初始化过程并得到容器之后,还有一个操作进行,比如:设置BeanFactory的后置处理器,设置Bean的后置处理器,初始化上下文的事件机制等等。

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

        // 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.
            // 设置BeanFactory的后置处理器
            postProcessBeanFactory(beanFactory);

            StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
            // Invoke factory processors registered as beans in the context.
            //调用BeanFactory的后处理器,这些后处理器是在Bean定义中向容器注册的
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            //注册Bean的后处理器,在Bean创建过程中调用
            registerBeanPostProcessors(beanFactory);
            beanPostProcess.end();

            // Initialize message source for this context.
            //对上下文中的消息源进行初始化
            initMessageSource();

            // Initialize event multicaster for this context.
            //初始化上下文中的事件机制
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            //初始化其他的特殊Bean
            onRefresh();

            // Check for listener beans and register them.
            //检查监听Bean并且将这些Bean向容器注册
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            //实例化所有的(non-lazy-init)单例
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            //发布容器事件.结束Refresh过程
            finishRefresh();
        }

        catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
            }

            // Destroy already created singletons to avoid dangling resources.
            //为防止Bean资源占用,在异常处理中,销毁巳经在前面过程中生成的单例Bean
            destroyBeans();

            // Reset 'active' flag.
            //重置"active"标志
            cancelRefresh(ex);

            // Propagate exception to caller.
            throw ex;
        }

        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
           resetCommonCaches();
            contextRefresh.end();
        }
    }
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号