Spring读书笔记——bean加载
我们的日常开发几乎离不开Spring,他为我们的开发带来了很大的便捷,那么Spring框架是如何做到方便他人的呢。今天就来说说bean如何被加载加载。
我们在xml文件中写过太多类似这样的bean声明
<bean id="jsonParser" class="com.jackie.json.FastjsonJsonParser" />
那么这样的声明是如果被Spring读取并加载的呢?
DefaultListableBeanFactory
继承关系
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable
上面是DefaultListableBeanFactory类源码的声明,集成了父类AbstractAutowireCapableBeanFactory以及实现了接口
ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable(且不管这些又长有难懂的父类和父接口都是干什么的)

上面是DefaultListableBeanFactory的所有依赖父类,可以看到最顶层使我们熟悉的Object类。
地位
DefaultListableBeanFactory类是整个bean加载的核心部分。后面我们要说到的XmlBeanFactory就是DefaultListableBeanFactory的子类。
XmlBeanFactory
XmlBeanFactory是DefaultListableBeanFactory的子类。其与DefaultListableBeanFactory类的不同之处通过看源码就会发现,XmlBeanFactory使用了自定义的XmlBeanDefinitionReader用于读取xml文件内容。
XmlBeanFactory的源码并不复杂
public class XmlBeanFactory extends DefaultListableBeanFactory {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
/**
* Create a new XmlBeanFactory with the given resource,
* which must be parsable using DOM.
* @param resource XML resource to load bean definitions from
* @throws BeansException in case of loading or parsing errors
*/
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, null);
}
/**
* Create a new XmlBeanFactory with the given input stream,
* which must be parsable using DOM.
* @param resource XML resource to load bean definitions from
* @param parentBeanFactory parent bean factory
* @throws BeansException in case of loading or parsing errors
*/
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
}
- 有两个构造函数
- 两个构造函数都有参数Resource,我们在调用前可以通过各种实现比如
new ClassPathResource("application-context.xml")的方式传值 - Resource有很多实现比如 文件(FileSystemResource)、URL资源(UrlResource)、InputStream资源(InputStreamResource)、Byte数组(ByteArrayResource)等
- 使用Resource是因为该接口抽象出了Spring用到的各种底层资源比如File、Url、Classpath等
bean加载过程
说到这里的bean加载就离不开我们上面提到的XmlBeanFactory类。
一切的加载XML以及解析bean的操作都要从XmlBeanFactory的
XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory)
说起。
步骤分析
- 理所当然,我们首先点击进入XmlBeanDefinitionReader类的loadBeanDefinitions方法。整个过程简单说就是:
1.首先对传入的Resouce进行封装,成为EncodeResource对象(之所以这么做,是考虑可以对于资源文件进行编码)。
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
- 得到Resource的输入流
InputStream inputStream = encodedResource.getResource().getInputStream();
3.调用doLoadBeanDefinitions方法
- 进入doLoadBeanDefinitions方法,我们可以看到方法实现也很简单
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
Document doc = this.documentLoader.loadDocument(
inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
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);
}
}
主要做了三件事
得到XML文件的验证模式
int validationMode = getValidationModeForResource(resource);
2.加载XML文件,得到对应的Document对象(这里可以发现是调用了this.documentLoader即DefaultDocmentLoader类)
Document doc = this.documentLoader.loadDocument(
inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
这里的解析成Document其实就是常规的SAX解析XML的操作。
3.根据得到的Document对象注册Bean
registerBeanDefinitions(doc, resource)
解析注册BeanDefinitions
上面的在得到Docment对象后,就是需要解析注册BeanDefinitions了。
进入registerBeanDefinitions方法我们可以看到其实现为
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
documentReader.setEnvironment(this.getEnvironment());
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
我们继续深入,则进入到类DefaultBeanDefinitionDocumentReaderregisterBeanDefinitions方法的doRegisterBeanDefinitions实现。
在这个方法里实现了对于XML中的bean真正的解析
protected void doRegisterBeanDefinitions(Element root) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
Assert.state(this.environment != null, "Environment must be set for evaluating profiles");
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.environment.acceptsProfiles(specifiedProfiles)) {
return;
}
}
// 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 = createHelper(this.readerContext, root, parent);
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
追踪该方法中的每一个方法就是具体执行解析xml并加载bean的过程,有兴趣可以打断点调试一遍。
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!如果您想持续关注我的文章,请扫描二维码,关注JackieZheng的微信公众号,我会将我的文章推送给您,并和您一起分享我日常阅读过的优质文章。

Spring读书笔记——bean加载的更多相关文章
- Spring读书笔记——bean解析
前情回顾 上篇<Spring读书笔记--bean加载>我们从代码角度介绍了有哪些类负责解析XML文件,又是如何一步步从XML格式脱变成我们熟悉的bean的,直到DefaultBeanDef ...
- Spring读书笔记——bean创建(上)
通过<Spring读书笔记--bean加载>和<Spring读书笔记--bean解析>,我们明白了两件事. Spring如何加载消化一个xml配置文件 Spring如何将xml ...
- Spring读书笔记——bean创建(下)
有关Spring加载bean系列,今天这是最后一篇了,主要接上篇对于从Spring容器中获取Bean的一些细节实现的补充. <Spring读书笔记--bean加载>--Spring如何加载 ...
- How Tomcat Works 读书笔记 八 加载器 上
Java的类加载器 具体资料见 http://blog.csdn.net/dlf123321/article/details/39957175 http://blog.csdn.net/dlf1233 ...
- spring源码阅读笔记06:bean加载之准备创建bean
上文中我们学习了bean加载的整个过程,我们知道从spring容器中获取单例bean时会先从缓存尝试获取,如果缓存中不存在已经加载的单例bean就需要从头开始bean的创建,而bean的创建过程是非常 ...
- 工厂模式模拟Spring的bean加载过程
一.前言 在日常的开发过程,经常使用或碰到的设计模式有代理.工厂.单例.反射模式等等.下面就对工厂模式模拟spring的bean加载过程进行解析,如果对工厂模式不熟悉的,具体可以先去学习一下工厂 ...
- (转) Spring读书笔记-----Spring的Bean之配置依赖
前一篇博客介绍了Spring中的Bean的基本概念和作用域(Spring读书笔记-----Spring的Bean之Bean的基本概念),现在介绍Spring Bean的基本配置. 从开始我们知道Jav ...
- 【Spring源码分析】Bean加载流程概览
代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. 很多朋友可能想看Spring源码,但是不知道应当如何入手去看,这个可以理解:Java开发者通常从事 ...
- 【Spring源码分析】Bean加载流程概览(转)
转载自:https://www.cnblogs.com/xrq730/p/6285358.html 代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. ...
随机推荐
- java设计模式系列之设计模式概要(1)
一.什么是设计模式 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性. ...
- iOS 环信集成单聊界面,出现消息重复问题
解决办法很简单,数据重复就是EaseMessageViewController和ChatViewController重复调用了这个吧?//通过会话管理者获取收发消息 [self tableViewDi ...
- ORACLE分区表、分区索引详解
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt160 ORACLE分区表.分区索引ORACLE对于分区表方式其实就是将表分段 ...
- xmanager无法弹出图形化界面。
- 【Beta】 第五次Daily Scrum Meeting
一.本次会议为第五次meeting会议 二.时间:10:00AM-10:20AM 地点:陆大楼 三.会议站立式照片 四.今日任务安排 成员 昨日任务 今日任务 林晓芳 帮助完善登录界面 对目前完成的模 ...
- 201521123007《Java程序设计》第8周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 2. 书面作业 本次作业题集集合 1. List中指定元素的删除(题目4-1) private static ...
- 201521123003《Java程序设计》第5周学习总结
1. 本章学习总结 1.1 尝试使用思维导图总结有关多态与接口的知识点. 参考资料: 百度脑图 XMind 2. 书面作业 Q1.代码阅读:Child压缩包内源代码 1.1 com.parent包中C ...
- 201521123069 《Java程序设计》 第10周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常与多线程相关内容. (1)我们可以利用堆栈追踪来获得异常发生的根源(堆栈追踪信息最顶层). (2)自定义异常:不是由Java系统 ...
- 201521123009 《Java程序设计》第12周学习总结
1. 本周学习总结 2. 书面作业 Q1:将Student对象(属性:int id, String name,int age,double grade)写入文件student.data.从文件读出显示 ...
- 201521123109《java程序设计》第十周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常与多线程相关内容. 2. 书面作业 本次PTA作业题集异常.多线程 1. finally 题目4-2 1.1 截图你的提交结果( ...