Spring源码解析之IOC容器初始化

什么是IOC

IOC(inversion of control)控制反转,所谓控制反转就是把我们原先代码中需要实现的对象创建,反转给容器来实现,必然的我们需要创建一个容器,同样的需要一种描述让容器知道需要创建对象和对象之前的关系,这个描述的具体表现就是我们可配置的文件。

DI(Dependency injection)依赖注入:就是对象是被动接受依赖类而不是自己主动去寻找,换言之就是对象不是从容器中查找它的依赖类而是在容器实例化的时候主动把它的依赖类注入给它。

我们从宏观的设计视角来俯瞰整个架构考虑,如果我们是ioc的设计者,我们该怎么解决如下问题:
对象和对象之间的关系怎么描述?
可以采取xml,properties文件或者注解的方式表示。

描述对象关系的文件放在哪里?
可能是classPath,filesystem,或者是url网络资源,servletContext等等。

有了配置文件之后,我们还需要对配置文件进行解析,
不同的配置文件对对象的描述不一样,如标准的,如自定义声明的,如何统一?在内部需要有一个统一的关于对象的定义,所以外部描述必须转化成统一的描述定义。

如何对不同的配置文件进行解析?
需要对不同的配置文件语法,采取不同的解析器。

Spring IOC体系架构

带着上述的问题我们正式进入Spring IOC源码之旅。
首先我们先抛出一些概念及定义

BeanFactory

Spring Bean 的创建是典型的工厂模式,这一系列的Bean 工厂,也即IOC 容器为开发者管理对象间的依赖关系提供了很多便利和基础服务,在Spring 中有许多的IOC 容器的实现供用户选择和使用,其相互关系如下:
在这里插入图片描述
其中BeanFactory 作为最顶层的一个接口类,它定义了IOC 容器的基本功能规范,BeanFactory 有三个重要的子类:ListableBeanFactory、HierarchicalBeanFactory 和AutowireCapableBeanFactory。但是从类图中我们可以发现最终的默认实现类是DefaultListableBeanFactory,它实现了所有的接口。那为何要定义这么多层次的接口呢?查阅这些接口的源码和说明发现,每个接口都有它使用的场合,它主要是为了区分在Spring 内部在操作过程中对象的传递和转化过程时,对对象的数据访问所做的限制。例如ListableBeanFactory 接口表示这些Bean 是可列表化的,而HierarchicalBeanFactory 表示的是这些Bean 是有继承关系的,也就是每个Bean 有可能有父Bean。AutowireCapableBeanFactory 接口定义Bean 的自动装配规则。这三个接口共同定义了Bean 的集合、Bean 之间的关系、以及Bean 行为

在BeanFactory 里只对IOC 容器的基本行为作了定义,根本不关心你的Bean 是如何定义怎样加载的。正如我们只关心工厂里得到什么的产品对象,至于工厂是怎么生产这些对象的,这个基本的接口不关心。而要知道工厂是如何产生对象的,我们需要看具体的IOC 容器实现,Spring 提供了许多IOC 容器的实现。比如GenericApplicationContext , ClasspathXmlApplicationContext 等。ApplicationContext 是Spring 提供的一个高级的IOC 容器,它除了能够提供IOC 容器的基本功能外,还为用户提供了以下的附加服务。从ApplicationContext 接口的实现,我们看出其特点:

1、支持信息源,可以实现国际化。(实现MessageSource 接口)
2、访问资源。(实现ResourcePatternResolver 接口,后面章节会讲到)
3、支持应用事件。(实现ApplicationEventPublisher 接口)

BeanDefinition

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

BeanDefinitionReader

Bean 的解析过程非常复杂,功能被分的很细,因为这里需要被扩展的地方很多,必须保证有足够的灵活性,以应对可能的变化。Bean 的解析主要就是对Spring 配置文件的解析。这个解析过程主要通过BeanDefintionReader 来完成,最后看看Spring 中BeanDefintionReader 的类结构图:
在这里插入图片描述
在XmlBeanDefinitionReader中主要包含以下几步的处理:

(1):通过继承AbstractBeanDefinitionReader中的方法,来使用ResourceLoader将资源文件路劲转换为对应的Resource文件。

(2):通过DocumentLoader对Resource文件进行转换,将Resource文件转换为Document文件。

(3):通过实现接口BeanDefinitionDocumentReader的DefaultBeanDefinitionDocumentReader类对 Document 进行解析,并使用BeanDefinitionParserDelegate对Element进行解析。

基于Xml 的IOC 容器的初始化

IOC 容器的初始化包括BeanDefinition 的Resource 定位、加载和注册这三个基本的过程。我们以ApplicationContext 为例讲解,ApplicationContext 系列容器也许是我们最熟悉的,因为Web 项目中使用的XmlWebApplicationContext 就属于这个继承体系,还有ClasspathXmlApplicationContext等,其继承体系如下图所示:
在这里插入图片描述
ApplicationContext 允许上下文嵌套,通过保持父上下文可以维持一个上下文体系。对于Bean 的查找可以在这个上下文体系中发生,首先检查当前上下文,其次是父上下文,逐级向上,这样为不同的Spring应用提供了一个共享的Bean 定义环境。

1. 寻找入口

还有一个我们用的比较多的ClassPathXmlApplicationContext,通过main()方法启动:

//1.
ApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
//2.
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
   this(new String[] {configLocation}, true, null);
}
//3.
public ClassPathXmlApplicationContext(
      String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
      throws BeansException {

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

还有像AnnotationConfigApplicationContext 、FileSystemXmlApplicationContext 、XmlWebApplicationContext 等都继承自父容器AbstractApplicationContext 主要用到了装饰器模式和策略模式,最终都是调用refresh()方法。

2. 获得配置路径

通过分析ClassPathXmlApplicationContext 的源代码可以知道, 在创建ClassPathXmlApplicationContext 容器时,构造方法做以下两项重要工作:首先,调用父类容器的构造方法(super(parent)方法)为容器设置好Bean 资源加载器。然后, 再调用父类AbstractRefreshableConfigApplicationContext 的setConfigLocations(configLocations)方法设置Bean 配置信息的定位路径。通过追踪ClassPathXmlApplicationContext 的继承体系, 发现其父类的父类AbstractApplicationContext 中初始化IOC 容器所做的主要源码如下:

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

	public AbstractApplicationContext() {
		this.resourcePatternResolver = getResourcePatternResolver();
	}

	public AbstractApplicationContext(@Nullable ApplicationContext parent) {
		this();
		setParent(parent);
	}
	
	//获取一个Spring Source 的加载器用于读入Spring Bean 配置信息
	protected ResourcePatternResolver getResourcePatternResolver() {
	    //AbstractApplicationContext 继承DefaultResourceLoader,因此也是一个资源加载器
        //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 setConfigLocations(@Nullable String... locations) {
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			this.configLocations = new String[locations.length];
			for (int i = 0; i < locations.length; i++) {
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
	}

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

ClassPathResource res = new ClassPathResource("a.xml,b.xml");
//多个资源文件路径之间可以是用” , ; \t\n”等分隔。
ClassPathResource res =new ClassPathResource(new String[]{"a.xml","b.xml"});

至此,SpringIOC 容器在初始化时将配置的Bean 配置信息定位为Spring 封装的Resource。

3. 开始启动

SpringIOC 容器对Bean 配置资源的载入是从refresh()函数开始的,refresh()是一个模板方法,规定了IOC 容器的启动流程, 有些逻辑要交给其子类去实现。它对Bean 配置资源进行载入ClassPathXmlApplicationContext 通过调用其父类AbstractApplicationContext 的refresh()函数启动整个IOC 容器对Bean 定义的载入过程,现在我们来详细看看refresh()中的逻辑处理:

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			//1、调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识
			prepareRefresh();
			// Tell the subclass to refresh the internal bean factory.
			//2、告诉子类启动refreshBeanFactory()方法,Bean 定义资源文件的载入从
            //子类的refreshBeanFactory()方法启动
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			// Prepare the bean factory for use in this context.
			//3、为BeanFactory 配置容器特性,例如类加载器、事件处理器等
			prepareBeanFactory(beanFactory);
			try {
				// Allows post-processing of the bean factory in context subclasses.
				//4、为容器的某些子类指定特殊的BeanPost 事件处理器
				postProcessBeanFactory(beanFactory);
				// Invoke factory processors registered as beans in the context.
				//5、调用所有注册的BeanFactoryPostProcessor 的Bean
				invokeBeanFactoryPostProcessors(beanFactory);
				// Register bean processors that intercept bean creation.
				//6、为BeanFactory 注册BeanPost 事件处理器.
                //BeanPostProcessor 是Bean 后置处理器,用于监听容器触发的事件
				registerBeanPostProcessors(beanFactory);
				// Initialize message source for this context.
				//7、初始化信息源,和国际化相关.
				initMessageSource();
				// Initialize event multicaster for this context.
				//8、初始化容器事件传播器.
				initApplicationEventMulticaster();
				// Initialize other special beans in specific context subclasses.
				//9、调用子类的某些特殊Bean 初始化方法
				onRefresh();
				// Check for listener beans and register them.
				//10、为事件传播器注册事件监听器.
				registerListeners();
				// Instantiate all remaining (non-lazy-init) singletons.
				//11、初始化所有剩余的单例Bean
				finishBeanFactoryInitialization(beanFactory);
				// Last step: publish corresponding event.
				//12、初始化容器的生命周期事件处理器,并发布容器的生命周期事件
				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.
				//13、销毁已创建的Bean
				destroyBeans();

				// Reset 'active' flag.
				//14、取消refresh 操作,重置容器的同步标识.
				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...
				//15、重设公共缓存
				resetCommonCaches();
			}
		}
	}

refresh()方法主要为IOC 容器Bean 的生命周期管理提供条件,Spring IOC 容器载入Bean 配置信息从其子类容器的refreshBeanFactory() 方法启动, 所以整个refresh() 中“ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();”这句以后代码的都是注册容器的信息源和生命周期事件,我们前面说的载入就是从这句代码开始启动。refresh()方法的主要作用是:在创建IOC 容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh 之后使用的是新建立起来的IOC 容器。它类似于对IOC 容器的重启,在新建立好的容器中对容器进行初始化,对Bean 配置资源进行载入。

4. 创建容器

obtainFreshBeanFactory()方法调用子类容器的refreshBeanFactory()方法,启动容器载入Bean 配置信息的过程,代码如下:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
       //这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的         refreshBeanFactory()方法
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}

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

protected final void refreshBeanFactory() throws BeansException {
        //如果已经有容器,销毁容器中的bean,关闭容器
		if (hasBeanFactory()) {
			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 定义。

5. 载入配置路径

AbstractRefreshableApplicationContext 中只定义了抽象的loadBeanDefinitions 方法,容器真正调用的是其子类AbstractXmlApplicationContext 对该方法的实现,AbstractXmlApplicationContext的主要源码如下:loadBeanDefinitions() 方法同样是抽象方法, 是由其子类实现的, 也即在AbstractXmlApplicationContext 中。

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);
	}
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
   reader.setValidating(this.validating);
}
//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);
   }
}
@Nullable
protected Resource[] getConfigResources() {
   return null;
}

以XmlBean 读取器的其中一种策略XmlBeanDefinitionReader 为例。XmlBeanDefinitionReader 调用其父类AbstractBeanDefinitionReader 的reader.loadBeanDefinitions()方法读取Bean 配置资源。由于我们使用ClassPathXmlApplicationContext 作为例子分析,因此getConfigResources 的返回值为null,因此程序执行reader.loadBeanDefinitions(configLocations)分支。

6. 分配路径处理策略

在XmlBeanDefinitionReader 的抽象父类AbstractBeanDefinitionReader 中定义了载入过程。AbstractBeanDefinitionReader 的loadBeanDefinitions()方法源码如下:

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
        //获取在IOC 容器初始化过程中设置的资源加载器 这里就是ApplicationContext ,走else
        ResourceLoader resourceLoader = getResourceLoader();
        if (resourceLoader == null) {
            throw new BeanDefinitionStoreException(
                    "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
        }

        if (resourceLoader instanceof ResourcePatternResolver) {
            // Resource pattern matching available.
            try {
                //将指定位置的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 {
            // Can only load single resources by absolute URL.
            //将指定位置的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;
        }
    }

对AbstractBeanDefinitionReader 的loadBeanDefinitions()方法源码分析可以看出该方法就做了两件事:首先,调用资源加载器的获取资源方法resourceLoader.getResource(location),获取到要加载的资源。其次,真正执行加载功能是其子类XmlBeanDefinitionReader 的loadBeanDefinitions()方法。在loadBeanDefinitions()方法中调用了AbstractApplicationContext 的getResources()方法,跟进去之后发现getResources()方法其实定义在ResourcePatternResolver 中,此时,我们有必要来看一下ResourcePatternResolver 的全类图:
在这里插入图片描述
从上面可以看到ResourceLoader 与ApplicationContext 的继承关系,可以看出其实际调用的是DefaultResourceLoader 中的getSource() 方法定位Resource , 因为ClassPathXmlApplicationContext 本身就是DefaultResourceLoader 的实现类,所以此时又回到了ClassPathXmlApplicationContext 中来。其实就是在容器初始化设置资源加载器的时候:

public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
        Assert.notNull(resourceLoader, "ResourceLoader must not be null");
        this.resourceLoader = resourceLoader;
    }

7. 解析配置文件路径

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

@Override
public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");

        for (ProtocolResolver protocolResolver : this.protocolResolvers) {
            Resource resource = protocolResolver.resolve(location, this);
            if (resource != null) {
                return resource;
            }
        }
        //如果是类路径的方式,那需要使用ClassPathResource 来得到bean 文件的资源对象
        if (location.startsWith("/")) {
            return getResourceByPath(location);
        }
        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 定位这种情况。在ClassPathResource 中完成了对整个路径的解析。这样,就可以从类路径上对IOC 配置文件进行加载,当然我们可以按照这个逻辑从任何地方加载,在Spring 中我们看到它提供的各种资源抽象,比如ClassPathResource、URLResource、FileSystemResource 等来供我们使用。上面我们看到的是定位Resource 的一个过程,而这只是加载过程的一部分。例如FileSystemXmlApplication 容器就重写了,通过子类的覆盖,巧妙地完成了将类路径变为文件路径的转换。getResourceByPath()方法

@Override
protected Resource getResourceByPath(String path) {
  if (path.startsWith("/")) {
    path = path.substring(1);
  }
  //这里使用文件系统资源对象来定义bean 文件
  return new FileSystemResource(path);
}

8. 开始读取配置内容

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

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
     try {
     //将资源文件转为InputStream 的IO 流
            InputStream inputStream = encodedResource.getResource().getInputStream();
            try {
                //从InputStream 中得到XML 的解析源
                InputSource inputSource = new InputSource(inputStream);
                if (encodedResource.getEncoding() != null) {
                    inputSource.setEncoding(encodedResource.getEncoding());
                }
                //这里是具体的读取过程
                return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
            }
            finally {//关闭从Resource 中得到的IO 流
                inputStream.close();
            }
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "IOException parsing XML document from " + encodedResource.getResource(), ex);
        }
        finally {
            currentResources.remove(encodedResource);
            if (currentResources.isEmpty()) {
                this.resourcesCurrentlyBeingLoaded.remove();
            }
        }
}
//从特定XML 文件中实际载入Bean 配置资源的方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)      throws BeanDefinitionStoreException {   
     try {      
//将XML 文件转换为DOM 对象,解析过程由documentLoader 实现      
Document doc = doLoadDocument(inputSource, resource);      
//这里是启动对Bean 定义解析的详细过程,该解析过程会用到Spring 的Bean 配置规则      
return registerBeanDefinitions(doc, resource);  
        }
 }

通过源码分析,载入Bean 配置信息的最后一步是将Bean 配置信息转换为Document 对象,该过程由documentLoader()方法实现。

9. 准备文档对象

DocumentLoader 将Bean 配置资源转换成Document 对象的源码如下:

@Override
//使用标准的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) {
				// Enforce namespace aware for 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 对象并将其注册到容器中的。

10. 分配解析策略

XmlBeanDefinitionReader 类中的doLoadBeanDefinition()方法是从特定XML 文件中实际载入Bean 配置资源的方法,该方法在载入Bean 配置资源之后将其转换为Document 对象,接下来调用registerBeanDefinitions() 启动Spring IOC 容器对Bean 定义的解析过程,registerBeanDefinitions()方法源码如下:

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;
	}

Bean 配置资源的载入解析分为以下两个过程:首先,通过调用XML 解析器将Bean 配置信息转换得到Document 对象,但是这些Document 对象并没有按照Spring 的Bean 规则进行解析。这一步是载入的过程其次,在完成通用的XML 解析之后,按照Spring Bean 的定义规则对Document 对象进行解析,其解析过程是在接口BeanDefinitionDocumentReader 的实现类DefaultBeanDefinitionDocumentReader 中实现。

11. 将配置载入内存

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

@Override
//根据Spring DTD 对Bean 的定义规则解析Bean 定义Document 对象
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
        //获得XML 描述符
        this.readerContext = readerContext;
        logger.debug("Loading bean definitions");
        //获得Document 的根元素
        Element root = doc.getDocumentElement();
        doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
   //具体的解析过程由BeanDefinitionParserDelegate 实现,
   //BeanDefinitionParserDelegate 中定义了Spring Bean 定义XML 文件的各种元素
   BeanDefinitionParserDelegate parent = this.delegate;
  //创建BeanDefinitionParserDelegate,用于完成真正的解析过程
   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);
         if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
            if (logger.isInfoEnabled()) {
               logger.info("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;
}

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);
   }
   else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
      // recurse
      doRegisterBeanDefinitions(ele);
   }
}

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
   // BeanDefinitionHolder 是对BeanDefinition 的封装,即Bean 定义的封装类
   BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
   //对Document 对象中<Bean>元素的解析由BeanDefinitionParserDelegate 实现
   // BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
   if (bdHolder != null) {
      bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
      try {
         // Register the final decorated instance.
         //向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);
      }
      // Send registration event.
      //在完成向Spring IOC 容器注册解析得到的Bean 定义之后,发送注册事件
      getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
   }
}

通过上述Spring IOC 容器对载入的Bean 定义Document 解析可以看出,我们使用Spring 时,在Spring 配置文件中可以使用<import>元素来导入IOC 容器所需要的其他资源,Spring IOC 容器在解析时会首先将指定导入的资源加载进容器中。使用<ailas>别名时,Spring IOC 容器首先将别名元素所定义的别名注册到容器中。对于既不是<import>元素,又不是<alias>元素的元素,即Spring 配置文件中普通的<bean>元素的解析由BeanDefinitionParserDelegate 类的parseBeanDefinitionElement()方法来实现。这个解析的过程非常复杂,我们在mini 版本的时候,就用properties 文件代替了。

12. 载入bean元素

Bean 配置信息中的<import><alias>元素解析在DefaultBeanDefinitionDocumentReader 中已经完成,对Bean 配置信息中使用最多的<bean>元素交由BeanDefinitionParserDelegate 来解析,其解析实现的源码如下:

//解析Bean 配置信息中的<Bean>元素,这个方法中主要处理<Bean>元素的id,name 和别名属性
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable 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<>();
        //将<Bean>元素中的所有name 属性值存放到别名中
        if (StringUtils.hasLength(nameAttr)) {
            String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_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);
                        // 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.
                        //为解析的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);
        }

        return null;
}


protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
		String foundName = null;

		if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
			foundName = beanName;
		}
		if (foundName == null) {
			foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
		}
		if (foundName != null) {
			error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
		}

		this.usedNames.add(beanName);
		this.usedNames.addAll(aliases);
	}

//详细对<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);
			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();
		}

		return null;
	}

只要使用过Spring,对Spring 配置文件比较熟悉的人,通过对上述源码的分析,就会明白我们在Spring配置文件中<Bean>元素的中配置的属性就是通过该方法解析和设置到Bean 中去的。注意:在解析<Bean>元素过程中没有创建和实例化Bean 对象,只是创建了Bean 对象的定义类BeanDefinition,将<Bean>元素中的配置信息设置到BeanDefinition 中作为记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean 对象。上面方法中一些对一些配置如元信息(meta)、qualifier 等的解析,我们在Spring 中配置时使用的也不多,我们在使用Spring 的<Bean>元素时,配置最多的是<property>属性,因此我们下面继续分析源码,了解Bean 的属性在解析时是如何设置的。

13. 载入property元素

BeanDefinitionParserDelegate 在解析<Bean>调用parsePropertyElements()方法解析<Bean>元素中的<property>属性子元素,解析源码如下:

public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
		NodeList nl = beanEle.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
				parsePropertyElement((Element) node, bd);
			}
		}
	}

public void parsePropertyElement(Element ele, BeanDefinition bd) {
		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 {
			if (bd.getPropertyValues().contains(propertyName)) {
				error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
				return;
			}
			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();
		}
	}

14. 载入property子元素

在BeanDefinitionParserDelegate 类中的parsePropertySubElement()方法对中的子元素解析

@Nullable
	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 <ref> element", ele);
					return null;
				}
			}
			if (!StringUtils.hasText(refName)) {
				error("<ref> 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);
		}
		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;
		}
	}

15. 载入list的子元素

在BeanDefinitionParserDelegate 类中的parseListElement()方法就是具体实现解析<property>元素中的<list>集合子元素经过对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 容器的初始化过程

16. 分配注册策略

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

//将解析的BeanDefinitionHold 注册到容器中
public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// Register bean definition under primary name.
		 //获取解析的BeanDefinition 的名称
		String beanName = definitionHolder.getBeanName();
		//向IOC 容器注册BeanDefinition
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		//如果解析的BeanDefinition 有别名,向容器为其注册别名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}

当调用BeanDefinitionReaderUtils 向IOC 容器注册解析的BeanDefinition 时,真正完成注册功能的是DefaultListableBeanFactory。

17. 向容器注册

DefaultListableBeanFactory 中使用一个HashMap 的集合对象存放IOC 容器中注册解析的BeanDefinition,向IOC 容器注册的主要源码如下:

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
@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 oldBeanDefinition;

        oldBeanDefinition = this.beanDefinitionMap.get(beanName);
        if (oldBeanDefinition != null) {
            if (!isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                        "': There is already [" + oldBeanDefinition + "] bound.");
            }
            else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
                // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
                            "' with a framework-generated bean definition: replacing [" +
                            oldBeanDefinition + "] with [" + beanDefinition + "]");
                }
            }
            else if (!beanDefinition.equals(oldBeanDefinition)) {
                if (this.logger.isInfoEnabled()) {
                    this.logger.info("Overriding bean definition for bean '" + beanName +
                            "' with a different definition: replacing [" + oldBeanDefinition +
                            "] with [" + beanDefinition + "]");
                }
            }
            else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Overriding bean definition for bean '" + beanName +
                            "' with an equivalent definition: replacing [" + oldBeanDefinition +
                            "] 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;
                    if (this.manualSingletonNames.contains(beanName)) {
                        Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                        updatedSingletons.remove(beanName);
                        this.manualSingletonNames = updatedSingletons;
                    }
                }
            }
            else {
                // Still in startup registration phase
                this.beanDefinitionMap.put(beanName, beanDefinition);
                this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
            }
            this.frozenBeanDefinitionNames = null;
        }
        //检查是否有同名的BeanDefinition 已经在IOC 容器中注册
        if (oldBeanDefinition != null || containsSingleton(beanName)) {
            //重置所有已经注册过的BeanDefinition 的缓存
            resetBeanDefinition(beanName);
        }
    }

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

IOC 容器初始化小结

现在通过上面的代码,总结一下IOC 容器初始化的基本步骤:
1、初始化的入口在容器实现中的refresh()调用来完成。
2、对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 实现BeanDefinitionRegistry 接口来实现。注册过程就是在IOC 容器内部维护的一个HashMap 来保存得到的BeanDefinition 的过程。这个HashMap 是IOC 容器持有Bean 信息的场所,以后对Bean 的操作都是围绕这个HashMap 来实现的。然后我们就可以通过BeanFactory 和ApplicationContext 来享受到Spring IOC 的服务了,在使用IOC容器的时候,我们注意到除了少量粘合代码,绝大多数以正确IOC 风格编写的应用程序代码完全不用关心如何到达工厂,因为容器将把这些对象与容器管理的其他对象钩在一起。基本的策略是把工厂放到已知的地方,最好是放在对预期使用的上下文有意义的地方,以及代码将实际需要访问工厂的地方。Spring本身提供了对声明式载入web 应用程序用法的应用程序上下文,并将其存储在ServletContext 中的框架实现。

在这里插入图片描述

传统的Spring项目中的初始化流程:

每一个整合spring框架的项目中,总是不可避免地要在web.xml中加入这样一段配置。

<!-- 配置spring核心监听器,默认会以 /WEB-INF/applicationContext.xml作为配置文件 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- contextConfigLocation参数用来指定Spring的配置文件 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

这段配置有何作用呢,通过ContextLoaderListener源码来分析一下

public class ContextLoaderListener extends ContextLoader implements ServletContextListener

继承ContextLoader有什么作用

ContextLoaderListener可以指定在Web应用程序启动时载入Ioc容器,正是通过ContextLoader来实现的,可以说是Ioc容器的初始化工作。

实现ServletContextListener又有什么作用

ServletContextListener接口里的函数会结合Web容器的生命周期被调用。因为ServletContextListener是ServletContext的监听者,如果ServletContext发生变化,会触发相应的事件,而监听器一直对事件监听,如果接收到了变化,就会做出预先设计好的相应动作。由于ServletContext变化而触发的监听器的响应具体包括:在服务器启动时,ServletContext被创建的时候,服务器关闭时,ServletContext将被销毁的时候等,相当于web的生命周期创建与效果的过程。

那么ContextLoaderListener的作用是什么

ContextLoaderListener的作用就是启动Web容器时,读取在contextConfigLocation中定义的xml文件,自动装配ApplicationContext的配置信息,并产生WebApplicationContext对象,然后将这个对象放置在ServletContext的属性里,这样我们只要得到Servlet就可以得到WebApplicationContext对象,并利用这个对象访问spring容器管理的bean。

简单来说,就是上面这段配置为项目提供了spring支持,初始化了Ioc容器。而ServletContextListener所触发的动作则是:

/**
* Receives notification that the web application initialization
* process is starting.
*
* <p>All ServletContextListeners are notified of context
* initialization before any filters or servlets in the web
* application are initialized.
 *
* @param sce the ServletContextEvent containing the ServletContext
* that is being initialized
*/
public void contextInitialized(ServletContextEvent sce);

然后进入父类 ContextLoader :

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  //省略代码
  servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  //....省略代码
}

然后进入:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
        if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
            // The application context id is still set to its original default value
            // -> assign a more useful id based on available information
            String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
            if (idParam != null) {
                wac.setId(idParam);
            }
            else {
                // Generate default id...
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }

        wac.setServletContext(sc);
        String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
        if (configLocationParam != null) {//这不就是我们上面说的定位资源。设置Bean 配置信息的定位路径的方法吗
            wac.setConfigLocation(configLocationParam);
        }

        // The wac environment's #initPropertySources will be called in any case when the context
        // is refreshed; do it eagerly here to ensure servlet property sources are in place for
        // use in any post-processing or initialization that occurs below prior to #refresh
        ConfigurableEnvironment env = wac.getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {
            ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
        }

        customizeContext(sc, wac);        //初始化
        wac.refresh();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值