前言

1.在讲BeanDefinition的载入和解析之前,我们先来看看什么是BeanDefinition。

Bean对象在Spring中是以BeanDefinition来描述的,也就是说在Spring中,BeanDefinition用来表示bean对象。

2. 对于Spring IOC容器,BeanDefinition的载入过程,相当于把Spring的配置文件转换成Spring的内部数据结构。

在上一篇中容器初始化各个父类方法调用图,如下图所示:

1.BeanDefinition的载入和解析

我们接着上一篇的代码,在AbstractBeanDefinitionReader的loadBeanDefinitions()中,我们定位到了Resource[],看下代码:

AbstractBeanDefinitionReader的loadBeanDefinitions

public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
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 {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
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.
Resource resource = resourceLoader.getResource(location);
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}

1.1. 将xml文件转换成DOM对象

通过getResouce()方法得到Resouce之后,那么就开始了真正加载Bean资源。因为Spring可以对应不同形式的BeanDefition,我们这里讲的是xml的形式,所以就需要到xmlBeanDefinitonReader的实现中去看源码。

XmlBeanDefinitionReader的loadBeanDefinitions()及doLoadBeanDefinitions()

public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
} Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//将资源文件转换为IO输入流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
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对象
Document doc = doLoadDocument(inputSource, resource);
//这里是启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则[下文讲解]
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}

上面的过程完成了两个动作:(1)资源文件转换成IO输入流;(2)将xml文件转换成DOM对象。至于解析xml文件的方法,里面是通过创建解析工厂,设置xml解析校验,通过工厂创建解析器,然后parse(),所以这个过程我们就不看了

1.2 按照Spring的Bean规则对Document对象进行解析

走主线:得到dom对象后,开始启动对bean定义的详细解析,来看registerBeanDefinition()方法

XmlBeanDefinitionReader的loadBeanDefinitions()方法

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {

BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//解析过程入口,BeanDefinitionDocumentReader只是个接口,具体的解析实现过程有实现类
//DefaultBeanDefinitionDocumentReader完成
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}

我们总结下上面那么多绕人的代码。其实就2个思想:

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

(2)其次,在完成通用的XML解析之后,按照Spring的bean规则对document对象进行解析。

按照Spring的Bean规则对Document对象解析的过程是在接口BeanDefinitionDocumentReader的实现类DefaultBeanDefinitionDocumentReader中实现的。OK,重点来了。(友情提示,会绕好几个方法。)

DefaultBeanDefinitionDocumentReader的registerBeanDefinitions()及doRegisterBeanDefinitions()方法

    @Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
/**
* Register each bean definition within the given root {@code <beans/>} element.
*/
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 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);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
return;
}
}
} preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root); this.delegate = parent;
}
/**
* Parse the elements at the root level in the document:
* "import", "alias", "bean".
* @param root the DOM root element of the document
*/
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}

上面这段代码又墨迹了一会,这里主要是看节点元素是否是Spring的规范,因为它允许我们自定义解析规范,那么正常我们是利用Spring的规则,所以我们来看parseDefaultElement(ele, delegate)方法

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

终于看到自己熟悉的一点东西了

1.3  Bean资源的解析

//解析bean资源
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//BeanDefinitionHolder是对BeanDefinition的封装,包括BeanDefinition,beanName,aliases
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
//向SpringIOC容器注册解析得到的bean定义
//这是bean定义向IOC容器注册的入口,实际上是放到一个map里面
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}

注意:在解析<Bean>元素过程中没有创建和实例化Bean对象,只是创建了Bean对象的定义类型BeanDefinition,将<Bean>元素中的配置信息设置到BeanDefiniton作记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean对象。

Spring IOC容器的初始化-(二)BeanDefinition的载入和解析的更多相关文章

  1. Spring IoC容器的初始化过程

    Spring IoC容器的初始化包括 BeanDefinition的Resource定位.载入和注册 这三个基本的过程.IoC容器的初始化过程不包含Bean依赖注入的实现.Bean依赖的注入一般会发生 ...

  2. Spring IOC容器的初始化-(三)BeanDefinition的注册

    ---恢复内容开始--- 前言 在上一篇中有一处代码是BeanDefiniton注册的入口,我们回顾一下. 1.BeanDefiniton在IOC容器注册 首先我们回顾两点,1. 发起注册的地方:2. ...

  3. Spring IOC容器的初始化—(一)Resource定位

    前言 上一篇博文“ Spring IOC是怎样启动的 ”中提到了refresh()方法,这个就是容器初始化的入口.容器初始化共有三个阶段: 第一阶段:Resource定位 第二阶段:BeanDefin ...

  4. Spring IOC容器的初始化流程

    IOC初始化流程 Resource定位:指对BeanDefinition的资源定位过程.Bean 可能定义在XML中,或者是一个注解,或者是其他形式.这些都被用Resource来定位, 读取Resou ...

  5. (spring-第7回【IoC基础篇】)BeanDefinition的载入与解析&&spring.schemas、spring.handlers的使用

    报错信息:Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http: ...

  6. 03.Spring IoC 容器 - 初始化

    基本概念 Spring IoC 容器的初始化过程在监听器 ContextLoaderListener 类中定义. 具体由该类的的 configureAndRefreshWebApplicationCo ...

  7. JavaEE互联网轻量级框架整合开发(书籍)阅读笔记(6):Spring IOC容器学习(概念、作用、Bean生命周期)

    一.IOC控制反转概念 控制反转(IOC)是一种通过描述(在Java中可以是XML或者是注解)并通过第三方去生产或获取特定对象的方式. 主动创建模式,责任在于开发者,而在被动模式下,责任归于Ioc容器 ...

  8. spring5源码分析系列(三)——IOC容器的初始化(一)

    前言: IOC容器的初始化包括BeanDefinition的Resource定位.载入.注册三个基本过程. 本文以ApplicationContext为例讲解,XmlWebApplicationCon ...

  9. Spring IOC容器分析(4) -- bean创建获取完整流程

    上节探讨了Spring IOC容器中getBean方法,下面我们将自行编写测试用例,深入跟踪分析bean对象创建过程. 测试环境创建 测试示例代码如下: package org.springframe ...

随机推荐

  1. Java:执行jar文件命令

    Java:执行jar文件命令 执行jar文件命令: java -jar test.jar win7系统切换目录命令: cd /d d:/test

  2. Mysql:实现分组查询拼接未分组同一字段字符group_concat()

    Mysql:实现分组查询拼接未分组同一字段字符group_concat() MySQL中,如果想实现将分组之后的多个数据合并到一列,可以使用group_concat函数,如下图所示: 在oralce中 ...

  3. MySQL数据库表分区功能详解

    1.什么是表分区? mysql数据库中的数据是以文件的形势存在磁盘上的,默认放在/mysql/data下面(可以通过my.cnf中的datadir来查看),一张表主要对应着三个文件,一个是frm存放表 ...

  4. 回溯算法 DFS深度优先搜索 (递归与非递归实现)

    回溯法是一种选优搜索法(试探法),被称为通用的解题方法,这种方法适用于解一些组合数相当大的问题.通过剪枝(约束+限界)可以大幅减少解决问题的计算量(搜索量). 基本思想 将n元问题P的状态空间E表示成 ...

  5. React-Native 常用组件学习资料链接

    以下链接是自己开发RN工程时参考的一些不错的资料,给喜欢学习的朋友分享以下. React-Native组件用法详解之ListViewhttp://www.jianshu.com/p/1293bb8ac ...

  6. XamlParseException异常

    一般出现System.Windows.Markup.XamlParseException的错误是由1.dll库加载错误,查询一下你程序中引用的dll你是否加载并引用到程序内.2.程序中引用的文件(tx ...

  7. os.path.abs()与os.path.realpath()的一点区别

    相同点 1. 两者都是返回绝对路径,如果参数path为空,则返回当前文件所在目录的绝对路径 当前py文件所在的目录是revise print(os.path.abspath("") ...

  8. Ubuntu 18.04 下 emscripten SDK 的安装

    Ubuntu 18.04 下 emscripten SDK 的安装http://kripken.github.io/emscripten-site/docs/getting_started/downl ...

  9. CSS控制文字只显示一行,超出部分显示省略号

    <p style="width: 300px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"&g ...

  10. 重新认识HBase,Cassandra列存储——本质是还是行存储,只是可以动态改变列(每行对应的数据字段)数量而已,当心不是parquet

    行先是以一种非常独特的方式被索引,随后Bigtable利用行键对数据进行分割,将它们分布到集群中.列可以被迅速地定义在行中,让Bigtable适用于大多数的非模式环境. 数据在表面上最初是由行进行排列 ...