Spring源码解析IOC

文章目录

什么是IOC

Spring IOC(Inversion of Control)容器是Spring Framework的核心。 它创建对象,配置和组装它们的依赖关系,管理它们的整个生命周期。 容器使用依赖注入 (DI) 来管理组成应用程序的组件。

Spring IOC容器中创建和管理的对象,即称为Bean。

IOC(Inversion of Control),其中文是控制反转,就是把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理。所谓的"控制反转"就是对组件对象控制权的转移,从程序代码本身转移到了外部容器,由容器来创建对象并管理对象之间的依赖关系,换句话说,把对象的创建和对象之间的调用过程,交给容器进行管理。这个过程基本上是 bean本身的逆过程(因此得名,控制反转),它通过使用类的直接构造或服务定位器模式等机制来控制其依赖项的实例化或位置。

为了实现IOC,那么必然的我们需要创建一个容器,即IOC容器,同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们可配置的文件或是注解申明。IOC容器根据对象的描述创建对象,形成Bean, 根据对象与对象的关系实现Bean的依赖注入,以及管理Bean的生命周期,我们的应用程序在需要使用Bean时直接从IOC容器拿来使用,而关于Bean的创建,初始化以及使用完毕后的回收与销毁等Bean的生命周期的管理均交给IOC容器管理。

IOC的作用
1. 方便解耦,简化开发:
  • 实现了类与类依赖关系的解耦,大家都注册在IOC容器当中,并不直接强耦合。有多种注入类的方式:xml配置、@Component 注解、@import、@Configuration等等
  • 实现了类的依赖关系和代码的解耦:把类的依赖关系,可以不通过修改代码,而是通过修改xml然后由容器来实现,这给非开发人员带来了很多便利
2. 单例缓存:
  • 基于容器注册,就可以灵活缓存,避免内存空间的浪费,提升创建bean的速度。如果通过new的方式,就无法做到。
3. 预处理:
  • 对Bean生成进行干预(init、构造函数、属性赋值、对象销毁)等过程进行干预
4. 父子容器:
  • MVC的实现就是很好的例子,既有一定的隔离性,又可以复用父容器的类
从简单的示例说起

在新创建的 module:dom-test 的 build.gradle 文件中,我们添加 spring-context 依赖,这个相当于 Maven 中的 pom.xml:

dependencies {
    compile(project(":spring-context"))
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

一个简单的类:OrderDaoImpl

package com.dom.dao.impl;

public class OrderDaoImpl {
    public void save() {
        System.out.println("order dao save ...");
    }
}
无IOC的案例

App main函数通过new创建和使用OrderDaoImpl对象:

package com.dom;

import com.dom.dao.impl.OrderDaoImpl;

public class App {
	public static void main(String[] args) {
		OrderDaoImpl orderDao = new OrderDaoImpl();
		orderDao.save();
	}
}

运行结果:

在这里插入图片描述

有IOC的案例(XML版)
  1. applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--1.导入spring的坐标spring-context,对应版本是5.2.19.RELEASE-->

    <!--2.配置bean-->
    <!--bean标签标示配置bean
    id属性标示给bean起名字
    class属性表示给bean定义类型-->
    <bean id="orderDao" class="com.dom.dao.impl.OrderDaoImpl"/>
</beans>
  1. App1 main函数:
package com.dom;

import com.dom.dao.impl.OrderDaoImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App1 {
    public static void main(String[] args) {
        //3.获取IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //4.获取bean(根据bean配置id获取)
        OrderDaoImpl orderDao = (OrderDaoImpl) ctx.getBean("orderDao");
        System.out.println("orderDao:: " + orderDao);
        orderDao.save();
    }
}

运行结果:
在这里插入图片描述

结合此案例,IOC容器的实现需要明确的以下几个问题或步骤:

1. 管理什么?

Dao对象: OrderDaoImplBean

2. 如何将被管理的对象告知IOC容器?

配置: applicationContext.xml (其中一种方式)

3. 被管理的对象交给IOC容器,如何获得IOC容器?

接口: ApplicationContext

4. IOC容器获得后,如何从容器中获得Bean?

接口方法: getBean

5. 使用Spring导入哪些坐标?

如上述的build.gradle所示(这里是gradle实例,如果是maven应用,就用pom.xml)。

IOC原理
1. 应用如何解耦?

在这里插入图片描述

2. IOC解耦的过程

Bean配置解析(这里基于XML配置),反射和工厂模式,反射原理使得我们通过对象的描述信息可生产出完整的对象,工厂模式使得IOC代码更加松耦合更合家里的生产Bean对象。

在这里插入图片描述

3. Bean的创建过程

在这里插入图片描述

4. IOC流程图

在这里插入图片描述

IOC两大核心体系
  • IOC思想基于IOC容器完成,IOC容器底层就是对象工厂(BeanFactory)。
  • IOC容器创建和管理对象的本质是由BeanFactory和BeanDefinition一起工作来实现。
1. BeanFactory

Spring Bean的创建是典型的工厂模式,这一系列的Bean工厂,也即IOC容器为开发者管理对象间的依赖关系提供了很多便利和基础服务,在Spring中有许多的IOC容器的实现供用户选择和使用,其相互关系如下:

在这里插入图片描述

其中BeanFactory作为最顶层的一个接口类,是Spring内部使用的接口(通常不提供给开发人员使用),它定义了IOC容器的基本功能规范,BeanFactory 有三个子类:ListableBeanFactory、HierarchicalBeanFactory 和AutowireCapableBeanFactory。但是从上图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory,他实现了所有的接口。那为何要定义这么多层次的接口呢?查阅这些接口的源码和说明发现,每个接口都有他使用的场合,它主要是为了区分在 Spring 内部在操作过程中对象的传递和转化过程中,对对象的数据访问所做的限制。例如 ListableBeanFactory 接口表示这些 Bean 是可列表的,而 HierarchicalBeanFactory 表示的是这些 Bean 是有继承关系的,也就是每个Bean 有可能有父 Bean。AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则。这四个接口共同定义了 Bean 的集合、Bean 之间的关系、以及 Bean 行为.

最基本的IOC容器接口BeanFactory

public interface BeanFactory {    
     
     //对FactoryBean的转义定义,因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象,    
     //如果需要得到工厂本身,需要转义           
     String FACTORY_BEAN_PREFIX = "&"; 
        
     //根据bean的名字,获取在IOC容器中得到bean实例    
     Object getBean(String name) throws BeansException;    
   
     //根据bean的名字和Class类型来得到bean实例,增加了类型安全验证机制。    
      Object getBean(String name, Class requiredType) throws BeansException;    
     
     //提供对bean的检索,看看是否在IOC容器有这个名字的bean    
      boolean containsBean(String name);    
     
     //根据bean名字得到bean实例,并同时判断这个bean是不是单例    
     boolean isSingleton(String name) throws NoSuchBeanDefinitionException;    
     
     //得到bean实例的Class类型    
     Class getType(String name) throws NoSuchBeanDefinitionException;    
     
     //得到bean的别名,如果根据别名检索,那么其原名也会被检索出来    
    String[] getAliases(String name);    
     
}

在BeanFactory里只对IOC容器的基本行为作了定义,根本不关心你的bean是如何定义怎样加载的。正如我们只关心工厂里得到什么的产品对象,至于工厂是怎么生产这些对象的,这个基本的接口不关心。

​ 而要知道工厂是如何产生对象的,我们需要看具体的IOC容器实现,spring提供了许多IOC容器的实现。比如XmlBeanFactory,ClasspathXmlApplicationContext等。其中XmlBeanFactory就是针对最基本的IOC容器的实现,这个IOC容器可以读取XML文件定义的BeanDefinition(XML文件中对bean的描述),如果说XmlBeanFactory是初级的基础版容器,ApplicationContext应该算容器中的高帅富.

​ ApplicationContext是Spring提供的一个高级的IOC容器,它是BeanFactory的子接口,除了能够提供IOC容器的基本功能外,还为用户提供了以下的附加服务(通常由开发人员使用)。

从ApplicationContext接口的实现,我们看出其特点:

  1. 支持信息源,可以实现国际化。(实现MessageSource接口)
  2. 访问资源。(实现ResourcePatternResolver接口,这个后面要讲)
  3. 支持应用事件。(实现ApplicationEventPublisher接口)

这两个接口BeanFactory 和ApplicationContext就是Spring提供IOC容器实现两种方式。

2. BeanDefinition

SpringIOC容器管理了我们定义的各种Bean对象及其相互的关系,Bean对象在Spring实现中是以BeanDefinition来描述的,其继承体系如下:

在这里插入图片描述

Bean 的解析过程非常复杂,功能被分的很细,因为这里需要被扩展的地方很多,必须保证有足够的灵活性,以应对可能的变化。Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过下图中的类完成:

在这里插入图片描述

IOC容器的初始化(源码解析)

(XML版,基于Spring 5.2.19.RELEASE)

IOC容器的初始化包括BeanDefinition的Resource定位、载入和注册这三个基本的过程。我们以ApplicationContext为例讲解,ApplicationContext系列容器也许是我们最熟悉的,因为web项目中使用的XmlWebApplicationContext就属于这个继承体系,还有ClasspathXmlApplicationContext等,其继承体系如下图所示:

在这里插入图片描述

ClassPathXmlApplicationContext -> ApplicationContext -> BeanFactory

1. ClasspathXmlApplicationContext的IOC容器流程
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml")

调用其构造函数

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

实际调用

	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}
2. 设置资源加载器和资源定位

通过分析ClassPathXmlApplicationContext的源代码可以知道,在创建ClassPathXmlApplicationContext容器时,构造方法做以下两项重要工作:

首先,调用父类容器的构造方法(super(parent)方法)为容器设置好Bean资源加载器。

然后,再调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations)方法设置Bean定义资源文件的定位路径。

通过追踪ClassPathXmlApplicationContext的继承体系,发现其父类的父类AbstractApplicationContext中初始化IOC容器所做的主要源码如下:

public abstract class AbstractApplicationContext extends DefaultResourceLoader  
        implements ConfigurableApplicationContext, DisposableBean {  
    //静态初始化块,在整个容器创建过程中只执行一次  
    static {  
        //为了避免应用程序在Weblogic8.1关闭时出现类加载异常加载问题,
        //加载IOC容器关闭事件(ContextClosedEvent)类  
        ContextClosedEvent.class.getName();  
    }  
	public AbstractApplicationContext() {
		this.resourcePatternResolver = getResourcePatternResolver();
	}

	/**
	 * Create a new AbstractApplicationContext with the given parent context.
	 * @param parent the parent context
	 */
	 //ClassPathXmlApplicationContext调用父类构造方法调用的就是该方法
	public AbstractApplicationContext(@Nullable ApplicationContext parent) {
		this();
		setParent(parent);
	}
    //获取一个Spring Source的加载器用于读入Spring Bean定义资源文件  
    protected ResourcePatternResolver getResourcePatternResolver() {  
        // AbstractApplicationContext继承DefaultResourceLoader,也是一个S  
        //Spring资源加载器,其getResource(String location)方法用于载入资源  
        return new PathMatchingResourcePatternResolver(this);  
    }   
……  
}

AbstractApplicationContext构造方法中调用PathMatchingResourcePatternResolver的构造方法创建Spring资源加载器:

public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {  
        Assert.notNull(resourceLoader, "ResourceLoader must not be null");  
        //设置Spring的资源加载器  
        this.resourceLoader = resourceLoader;  
} 

在设置容器的资源加载器之后,接下来ClassPathXmlApplicationContext执行setConfigLocations方法通过调用其父类AbstractRefreshableConfigApplicationContext的方法进行对Bean定义资源文件的定位,该方法的源码如下:

//处理单个资源文件路径为一个字符串的情况  
    public void setConfigLocation(String location) {  
       //String CONFIG_LOCATION_DELIMITERS = ",; /t/n";  
       //即多个资源文件路径之间用” ,; /t/n”分隔,解析成数组形式  
        setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));  
    }  
    //解析Bean定义资源文件的路径,处理多个资源文件字符串数组  
     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++) {  
                // resolvePath为同一个类中将字符串解析为路径的方法  
                this.configLocations[i] = resolvePath(locations[i]).trim();  
            }  
        }  
        else {  
            this.configLocations = null;  
        }  
    }

通过这两个方法的源码我们可以看出,我们既可以使用一个字符串来配置多个Spring Bean定义资源文件,也可以使用字符串数组,即下面两种方式都是可以的:

a. ClasspathResource res = new ClasspathResource(“a.xml,b.xml,……”);

多个资源文件路径之间可以是用” ,; /t/n”等分隔。

b. ClasspathResource res = new ClasspathResource(newString[]{“a.xml”,”b.xml”,……});

至此,Spring IOC容器在初始化时将配置的Bean定义资源文件定位为Spring封装的Resource。

3. AbstractApplicationContext的refresh函数载入Bean定义过程

Spring IOC容器对Bean定义资源的载入是从refresh()函数开始的,refresh()是一个模板方法,refresh()方法的作用是:在创建IOC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IOC容器。refresh的作用类似于对IOC容器的重启,在新建立好的容器中对容器进行初始化,对Bean定义资源进行载入

ClassPathXmlApplicationContext通过调用其父类AbstractApplicationContext的refresh()函数启动整个IOC容器对Bean定义的载入过程:

public void refresh() throws BeansException, IllegalStateException {
       synchronized (this.startupShutdownMonitor) {
           //调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识
           prepareRefresh();
           //告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从
          //子类的refreshBeanFactory()方法启动
           ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
           //为BeanFactory配置容器特性,例如类加载器、事件处理器等
           prepareBeanFactory(beanFactory);
           try {
               //为容器的某些子类指定特殊的BeanPost事件处理器
               postProcessBeanFactory(beanFactory);
               //调用所有注册的BeanFactoryPostProcessor的Bean
               invokeBeanFactoryPostProcessors(beanFactory);
               //为BeanFactory注册BeanPost事件处理器.
               //BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件
               registerBeanPostProcessors(beanFactory);
               //初始化信息源,和国际化相关.
               initMessageSource();
               //初始化容器事件传播器.
               initApplicationEventMulticaster();
               //调用子类的某些特殊Bean初始化方法
               onRefresh();
               //为事件传播器注册事件监听器.
               registerListeners();
               //初始化所有剩余的单态Bean.
               finishBeanFactoryInitialization(beanFactory);
               //初始化容器的生命周期事件处理器,并发布容器的生命周期事件
               finishRefresh();
           }
           catch (BeansException ex) {
               //销毁以创建的单态Bean
               destroyBeans();
               //取消refresh操作,重置容器的同步标识.
               cancelRefresh(ex);
               throw ex;
           }
       }
   }

refresh()方法主要为IOC容器Bean的生命周期管理提供条件,Spring IOC容器载入Bean定义资源文件从其子类容器的refreshBeanFactory()方法启动,所以整个refresh()中“ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();”这句以后代码的都是注册容器的信息源和生命周期事件,载入过程就是从这句代码启动。

refresh()方法的作用是:在创建IOC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IOC容器。refresh的作用类似于对IOC容器的重启,在新建立好的容器中对容器进行初始化,对Bean定义资源进行载入

AbstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的refreshBeanFactory()方法,启动容器载入Bean定义资源文件的过程,代码如下:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的refreshBeanFactory()方法
    refreshBeanFactory();
    return getBeanFactory();
}

AbstractApplicationContext子类的refreshBeanFactory()方法:

AbstractApplicationContext类中只抽象定义了refreshBeanFactory()方法,容器真正调用的是其子类AbstractRefreshableApplicationContext实现的 refreshBeanFactory()方法,方法的源码如下:

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定义。

4. AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法:

AbstractRefreshableApplicationContext中只定义了抽象的loadBeanDefinitions方法,容器真正调用的是其子类AbstractXmlApplicationContext对该方法的实现,AbstractXmlApplicationContext的主要源码如下:

loadBeanDefinitions方法同样是抽象方法,是由其子类实现的,也即在AbstractXmlApplicationContext中。

public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
    ……
    //实现父类抽象的载入Bean定义方法
    @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读取器加载Bean定义资源
   protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
       //获取Bean定义资源的定位
       Resource[] configResources = getConfigResources();
       if (configResources != null) {
           //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
           //的Bean定义资源
           reader.loadBeanDefinitions(configResources);
       }
       //如果子类中获取的Bean定义资源定位为空,则获取ClassPathXmlApplicationContext构造方法中setConfigLocations方法设置的资源
       String[] configLocations = getConfigLocations();
       if (configLocations != null) {
           //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
           //的Bean定义资源
           reader.loadBeanDefinitions(configLocations);
       }
   }
   //这里又使用了一个委托模式,调用子类的获取Bean定义资源定位的方法
   //该方法在ClassPathXmlApplicationContext中进行实现
   protected Resource[] getConfigResources() {
       return null;
   }   ……
}

Xml Bean读取器(XmlBeanDefinitionReader)调用其父类AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法读取Bean定义资源。

5. AbstractBeanDefinitionReader读取Bean定义资源:

AbstractBeanDefinitionReader的loadBeanDefinitions方法源码如下:

可以到org.springframework.beans.factory.support看一下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方法。
在这里插入图片描述
在这里插入图片描述

看到第8、16行,结合上面的ResourceLoader与ApplicationContext的继承关系图,可以知道此时调用的是DefaultResourceLoader中的getSource()方法定位Resource,因为ClassPathXmlApplicationContext本身就是DefaultResourceLoader的实现类,所以此时又回到了ClassPathXmlApplicationContext中来。

6. 资源加载器获取要读入的资源:

XmlBeanDefinitionReader通过调用其父类DefaultResourceLoader的getResource方法获取要加载的资源,其源码如下

	//获取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;
			}
		}

		if (location.startsWith("/")) {
			return getResourceByPath(location);
		}
		//如果是类路径的方式,那需要使用ClassPathResource 来得到bean 文件的资源对象
		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 方式,使用UrlResource 作为bean 文件的资源对象
				URL url = new URL(location);
				return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
                //如果既不是classpath标识,又不是URL标识的Resource定位,则调用
                //容器本身的getResourceByPath方法获取Resource
				return getResourceByPath(location);
			}
		}
	}

DefaultResourceLoader提供了getResourceByPath方法的实现,就是为了处理既不是classpath标识,又不是URL标识的Resource定位这种情况。

	protected Resource getResourceByPath(String path) {
		return new ClassPathContextResource(path, getClassLoader());
	}

	/**
	 * Create a new {@code ClassPathResource} for {@code ClassLoader} usage.
	 * A leading slash will be removed, as the ClassLoader resource access
	 * methods will not accept it.
	 * @param path the absolute path within the classpath
	 * @param classLoader the class loader to load the resource with,
	 * or {@code null} for the thread context class loader
	 * @see ClassLoader#getResourceAsStream(String)
	 */
	 //这里使用classpath资源路径下的配置文件来定义bean
	public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
		Assert.notNull(path, "Path must not be null");
		String pathToUse = StringUtils.cleanPath(path);
		if (pathToUse.startsWith("/")) {
			pathToUse = pathToUse.substring(1);
		}
		this.path = pathToUse;
		this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
	}

这样代码就回到了 ClassPathXmlApplicationContext 中来,他提供了ClassPathResource 来得到配置文件的资源定义。

这样,就可以从文件系统路径上对IOC 配置文件进行加载 - 当然我们可以按照这个逻辑从任何地方加载,在Spring 中我们看到它提供 的各种资源抽象,比如ClassPathResource, URLResource,FileSystemResource 等来供我们使用。上面我们看到的是定位Resource 的一个过程,而这只是加载过程的一部分。

7. XmlBeanDefinitionReader加载Bean定义资源:

Bean定义的Resource得到了

继续回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean文件的资源定义以后的载入过程。

//XmlBeanDefinitionReader加载资源的入口方法  
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {  
    //将读入的XML资源进行特殊编码处理  
    return loadBeanDefinitions(new EncodedResource(resource));  
} 
	/**
	 * Load bean definitions from the specified XML file.
	 * @param encodedResource the resource descriptor for the XML file,
	 * allowing to specify an encoding to use for parsing the file
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 */
	 //这里是载入XML形式Bean定义资源文件方法
	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<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}

		//将资源文件转为InputStream的IO流
		try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			//从InputStream中得到XML的解析源
			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();
			}
		}
	}

    .........    
  	/**
	 * Actually load bean definitions from the specified XML file.
	 * @param inputSource the SAX InputSource to read from
	 * @param resource the resource descriptor for the XML file
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 * @see #doLoadDocument
	 * @see #registerBeanDefinitions
	 */
	 //从特定XML文件中实际载入Bean定义资源的方法
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			Document doc = doLoadDocument(inputSource, resource);
			//这里是启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则
			int count = registerBeanDefinitions(doc, resource);
			......
			}
		}

	/**
	 * Actually load the specified document using the configured DocumentLoader.
	 * @param inputSource the SAX InputSource to read from
	 * @param resource the resource descriptor for the XML file
	 * @return the DOM Document
	 * @throws Exception when thrown from the DocumentLoader
	 * @see #setDocumentLoader
	 * @see DocumentLoader#loadDocument
	 */
	protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
		//将XML文件转换为DOM对象,解析过程由documentLoader实现 
		return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
				getValidationModeForResource(resource), isNamespaceAware());
	}

通过源码分析,载入Bean定义资源文件的最后一步是将Bean定义资源转换为Document对象,该过程由documentLoader实现

8. DocumentLoader将Bean定义资源转换为Document对象:

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对象并将其注册到容器中的。

9. XmlBeanDefinitionReader解析载入的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 BeanUtils.instantiateClass(this.documentReaderClass);
}

Bean定义资源的载入解析分为以下两个过程:

首先,通过调用XML解析器将Bean定义资源文件转换得到Document对象,但是这些Document对象并没有按照Spring的Bean规则进行解析。这一步是载入的过程

其次,在完成通用的XML解析之后,按照Spring的Bean规则对Document对象进行解析。

按照Spring的Bean规则对Document对象解析的过程是在接口BeanDefinitionDocumentReader的实现类DefaultBeanDefinitionDocumentReader中实现的。

10. DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析:

BeanDefinitionDocumentReader接口通过registerBeanDefinitions方法调用其实现类DefaultBeanDefinitionDocumentReader对Document对象进行解析,解析的代码如下

	/**
	 * This implementation parses bean definitions according to the "spring-beans" XSD
	 * (or DTD, historically).
	 * <p>Opens a DOM Document; then initializes the default settings
	 * specified at the {@code <beans/>} level; then parses the contained bean definitions.
	 */
	 //根据Spring DTD对Bean的定义规则解析Bean定义Document对象
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}
	/**
	 * Register each bean definition within the given root {@code <beans/>} element.
	 */
	@SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
	protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		//具体的解析过程由BeanDefinitionParserDelegate实现,  
		//BeanDefinitionParserDelegate中定义了Spring Bean定义XML文件的各种元素
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}
		//在解析Bean定义之前,进行自定义的解析,增强解析过程的可扩展性
		preProcessXml(root);
		//从Document的根元素开始进行Bean定义的Document对象
		parseBeanDefinitions(root, this.delegate);
		//在解析Bean定义之后,进行自定义的解析,增加解析过程的可扩展性
		postProcessXml(root);

		this.delegate = parent;
	}
	//创建BeanDefinitionParserDelegate,用于完成真正的解析过程
	protected BeanDefinitionParserDelegate createDelegate(
			XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {

		BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
		delegate.initDefaults(root, parentDelegate);
		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);
		}
		//如果有子Bean,就递归
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
   //解析<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));
       }
   }

通过上述Spring IOC容器对载入的Bean定义Document解析可以看出,我们使用Spring时,在Spring配置文件中可以使用元素来导入IOC容器所需要的其他资源,Spring IOC容器在解析时会首先将指定导入的资源加载进容器中。使用别名时,Spring IOC容器首先将别名元素所定义的别名注册到容器中。

对于既不是元素,又不是元素的元素,即Spring配置文件中普通的元素的解析由BeanDefinitionParserDelegate类的parseBeanDefinitionElement方法来实现。

11. BeanDefinitionParserDelegate解析Bean定义资源文件中的元素:

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和别名等属性进行了处理,该方法中主要处理除这三个以外的其他属性数据
	@Nullable
	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, @Nullable 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();
		}
		//如果<Bean>元素中配置了parent属性,则获取parent属性的值
		String parent = null;
		if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
			parent = ele.getAttribute(PARENT_ATTRIBUTE);
		}

		try {
			//根据<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的属性在解析时是如何设置的。

12. BeanDefinitionParserDelegate解析元素

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 方法解析,我们继续分析该方法的源码,了解其解析过程。

13. 解析元素的子元素

在BeanDefinitionParserDelegate类中的parsePropertySubElement方法对中的子元素解析,源码如下:

	//解析<property>元素中ref,value或者集合等子元素
	@Nullable
	public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable 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)) {
			// A generic reference to any name of any bean.
			//获取<property>元素中的bean属性值,引用其他解析的Bean的名称
			//可以不再同一个Spring配置文件中,具体请参考Spring对ref的配置规则
			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.
				//获取<property>元素中parent属性值,引用父级容器中的Bean
				refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
				toParent = true;
				if (!StringUtils.hasLength(refName)) {
					error("'bean' 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)) {
			// 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;
		}
		//如果子元素是<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的数据封装,对集合数据类型的具体解析有各自的解析方法实现,解析方法的命名非常规范,一目了然,我们对集合元素的解析方法进行源码分析,了解其实现过程。

14. 解析子元素:

在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容器的初始化过程。

15. 解析过后的BeanDefinition在IOC容器中的注册:

让我们继续跟踪程序的执行顺序,接下来会到我们第3步中分析DefaultBeanDefinitionDocumentReader对Bean定义转换的Document对象解析的流程中,在第10步中其parseDefaultElement方法中完成对Document对象的解析后得到封装BeanDefinition的BeanDefinitionHolder对象,然后调用DefaultBeanDefinitionDocumentReader的其中方法processBeanDefinition中调用BeanDefinitionReaderUtils的registerBeanDefinition方法向IOC容器注册解析的Bean,BeanDefinitionReaderUtils的注册的源码如下:

/**
	 * Process the given bean element, parsing the bean definition
	 * and registering it with the registry.
	 */
//解析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));
    }
}
//将解析的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。

16. DefaultListableBeanFactory向IOC容器注册解析后的BeanDefinition:

DefaultListableBeanFactory中使用一个HashMap的集合对象存放IOC容器中注册解析的BeanDefinition,向IOC容器注册的主要源码如下:
在这里插入图片描述

    //存储注册的俄BeanDefinition  
    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();    
	//---------------------------------------------------------------------
	// Implementation of BeanDefinitionRegistry interface
	//---------------------------------------------------------------------
	//向IOC容器注册解析的BeanDefiniton
	@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");
		//校验解析的BeanDefiniton 
		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		//检查是否有同名的BeanDefinition已经在IOC容器中注册,如果已经注册,
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				//并且不允许覆盖已注册的Bean,则抛出注册失败异常
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			//如果允许覆盖,则同名的Bean,后注册的覆盖先注册的 
			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<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					removeManualSingletonName(beanName);
				}
			}
			else {
				// Still in startup registration phase
				//IOC容器中没有已经注册同名的Bean,按正常注册流程注册
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			//重置所有已经注册过的BeanDefinition的缓存 
			resetBeanDefinition(beanName);
		}
		else if (isConfigurationFrozen()) {
			clearByTypeCache();
		}
	}

至此,Bean定义资源文件中配置的Bean被解析过后,已经注册到IOC容器中,被容器管理起来,真正完成了IOC容器初始化所做的全部工作。现在IOC容器中已经建立了整个Bean的配置信息,这些BeanDefinition信息已经可以使用,并且可以被检索,IOC容器的作用就是对这些注册的Bean定义信息进行处理和维护。这些的注册的Bean定义信息是IOC容器控制反转的基础,正是有了这些注册的数据,容器才可以进行依赖注入。

总结:

现在通过上面的代码,总结一下IOC容器初始化的基本步骤:

  • 初始化的入口在容器实现中的 refresh()调用来完成

  • 对 bean 定义载入 IOC 容器使用的方法是 loadBeanDefinition,其中的大致过程如下:通过 ResourceLoader 来完成资源文件位置的定位,DefaultResourceLoader 是默认的实现,同时上下文本身就给出了 ResourceLoader 的实现,可以从类路径,文件系统, URL 等方式来定为资源位置。如果是 XmlBeanFactory作为 IOC 容器,那么需要为它指定 bean 定义的资源,也就是说 bean 定义文件时通过抽象成 Resource 来被 IOC 容器处理的,容器通过 BeanDefinitionReader来完成定义信息的解析和 Bean 信息的注册,往往使用的是XmlBeanDefinitionReader 来解析 bean 的 xml 定义文件 - 实际的处理过程是委托给 BeanDefinitionParserDelegate 来完成的,从而得到 bean 的定义信息,这些信息在 Spring 中使用 BeanDefinition 对象来表示 - 这个名字可以让我们想到loadBeanDefinition,RegisterBeanDefinition 这些相关的方法 - 他们都是为处理 BeanDefinitin 服务的, 容器解析得到 BeanDefinition IOC 以后,需要把它在 IOC 容器中注册,这由 IOC 实现 BeanDefinitionRegistry 接口来实现。注册过程就是在 IOC 容器内部维护的一个HashMap 来保存得到的 BeanDefinition 的过程。这个 HashMap 是 IOC 容器持有 bean 信息的场所,以后对 bean 的操作都是围绕这个HashMap 来实现的.

  • 然后我们就可以通过 BeanFactory 和 ApplicationContext 来享受到 Spring IOC 的服务了,在使用 IOC 容器的时候,我们注意到除了少量粘合代码,绝大多数以正确 IOC 风格编写的应用程序代码完全不用关心如何到达工厂,因为容器将把这些对象与容器管理的其他对象钩在一起。基本的策略是把工厂放到已知的地方,最好是放在对预期使用的上下文有意义的地方,以及代码将实际需要访问工厂的地方。 Spring 本身提供了对声明式载入 web 应用程序用法的应用程序上下文,并将其存储在ServletContext 中的框架实现。具体可以参见以后的文章

在使用 Spring IOC 容器的时候我们还需要区别两个概念:

​ Beanfactory 和 Factory bean,其中 BeanFactory 指的是 IOC 容器的编程抽象,比如 ApplicationContext, XmlBeanFactory 等,这些都是 IOC 容器的具体表现,需要使用什么样的容器由客户决定,但 Spring 为我们提供了丰富的选择。 FactoryBean 只是一个可以在 IOC而容器中被管理的一个 bean,是对各种处理过程和资源使用的抽象,Factory bean 在需要时产生另一个对象,而不返回 FactoryBean本身,我们可以把它看成是一个抽象工厂,对它的调用返回的是工厂生产的产品。所有的 Factory bean 都实现特殊的org.springframework.beans.factory.FactoryBean 接口,当使用容器中 factory bean 的时候,该容器不会返回 factory bean 本身,而是返回其生成的对象。Spring 包括了大部分的通用资源和服务访问抽象的 Factory bean 的实现,其中包括:对 JNDI 查询的处理,对代理对象的处理,对事务性代理的处理,对 RMI 代理的处理等,这些我们都可以看成是具体的工厂,看成是SPRING 为我们建立好的工厂。也就是说 Spring 通过使用抽象工厂模式为我们准备了一系列工厂来生产一些特定的对象,免除我们手工重复的工作,我们要使用时只需要在 IOC 容器里配置好就能很方便的使用了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值