Spring容器基础xmlbeanfactory(一起看源码)
在spring中,如果你想创建容器少不了使用常见的xmlbeanfactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,在这里,不介绍后两者。即使xmlbeanfactory已经过时了,但是有必要还是说一说。创建容器的代码:BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContextIOC.xml"));发现这里的构造函数中的参数是ClassPathResource类,这个类的作用就是加载配置文件,也就是说spring的配置文件的加载少不了这个类。这个类它是怎样加载文件的,我们一起追踪它的执行流程。

Resource是ClassPathResource实现的接口,Resource继承了InputStreamSource接口。在InputStreamSource这个接口里面只有一个方法,一起来看一下。

这说明拿到了输入流,这样我们就可以对文件做操作。此时,Resource接口有这些方法。

足以说明Resource接口封装底层资源,这些方法这里不过多介绍了。其中,exists,isReadable,isOpen是判断当前资源状态的方法。通过以上完成了对配置文件的封装,接下来介绍XmlBeanFactory的初始化过程。XmlBeanFactory类的构造函数有这样几个:

这里使用构造函数参数为Resource,进入这个方法后,看到这样的一串代码
我们点进去this(resource,null),调用的是XmlBeanFactory(Resource, BeanFactory)这个构造函数。
通过追踪super(parentBeanFactory);可以猜到使用ignoreDependencyInterface忽略了给定接口的自动装配功能。源码如下:

在XmlBeanFactory构造函数中,资源加载的核心代码是:this.reader.loadBeanDefinitions(resource);资源加载完成之后,接下来就是读取,在XmlBeanFactory构造函数中调用了this.reader.loadBeanDefinitions(resource);再一次追踪一下这串代码:
可以大致猜到以上代码主要作用对资源文件的编码进行处理,追踪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
*/
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 {
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();
}
}
}
以上源码中,红色才是核心所在。追踪此代码:
/**
* 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
*/
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource);
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);
}
}
以上代码其实就是要拿到Document,通过Document注册Bean信息。再一次追踪源代码:
/**
* Register the bean definitions contained in the given DOM document.
* Called by {@code loadBeanDefinitions}.
* <p>Creates a new instance of the parser class and invokes
* {@code registerBeanDefinitions} on it.
* @param doc the DOM document
* @param resource the resource descriptor (for context information)
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of parsing errors
* @see #loadBeanDefinitions
* @see #setDocumentReaderClass
* @see BeanDefinitionDocumentReader#registerBeanDefinitions
*/
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
追踪documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
/**
* 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.
*/
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
最后一句代码doRegisterBeanDefinitions(root);开始进行对XML解析,核心源码有必要给大家看一下:
/**
* 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;
}
解析并注册BeanDefinitions,源代码如下:
/**
* 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容器基础xmlbeanfactory(一起看源码)的更多相关文章
- 专治不会看源码的毛病--spring源码解析AOP篇
昨天有个大牛说我啰嗦,眼光比较细碎,看不到重点.太他爷爷的有道理了!要说看人品,还是女孩子强一些.原来记得看到一个男孩子的抱怨,说怎么两人刚刚开始在一起,女孩子在心里就已经和他过完了一辈子.哥哥们,不 ...
- Spring AOP源码解析——专治你不会看源码的坏毛病!
昨天有个大牛说我啰嗦,眼光比较细碎,看不到重点.太他爷爷的有道理了!要说看人品,还是女孩子强一些. 原来记得看到一个男孩子的抱怨,说怎么两人刚刚开始在一起,女孩子在心里就已经和他过完了一辈子.哥哥们, ...
- Spring系列28:@Transactional事务源码分析
本文内容 @Transactional事务使用 @EnableTransactionManagement 详解 @Transactional事务属性的解析 TransactionInterceptor ...
- spring MVC cors跨域实现源码解析
# spring MVC cors跨域实现源码解析 > 名词解释:跨域资源共享(Cross-Origin Resource Sharing) 简单说就是只要协议.IP.http方法任意一个不同就 ...
- Spring Boot 2.x 启动全过程源码分析(上)入口类剖析
Spring Boot 的应用教程我们已经分享过很多了,今天来通过源码来分析下它的启动过程,探究下 Spring Boot 为什么这么简便的奥秘. 本篇基于 Spring Boot 2.0.3 版本进 ...
- Spring 循环引用(二)源码分析
Spring 循环引用(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring 循环引用相关文章: & ...
- Spring Boot REST(二)源码分析
Spring Boot REST(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) SpringBoot RE ...
- Spring注解之@Lazy注解,源码分析和总结
一 关于延迟加载的问题,有次和大神讨论他会不会直接或间接影响其他类.spring的好处就是文档都在代码里,网上百度大多是无用功. 不如,直接看源码.所以把当时源码分析的思路丢上来一波. 二 源码分析 ...
- spring MVC cors跨域实现源码解析 CorsConfiguration UrlBasedCorsConfigurationSource
spring MVC cors跨域实现源码解析 spring MVC cors跨域实现源码解析 名词解释:跨域资源共享(Cross-Origin Resource Sharing) 简单说就是只要协议 ...
随机推荐
- Android ImageView 获取图片信息后进行比较
ImageView a=(ImageView)findViewById(R.id.imageView2); //获取当前图片ConstantState类对象 Drawable.ConstantStat ...
- 查看执行计划plustrace:set autotrace trace exp stat(SP2-0618、SP2-0611)
执行计划是SQL获取和处理数据的途径和方法. 执行计划和性能 SQL -- 数据库性能的始作俑者 所有的数据库性能,几乎全部来自SQL. 优秀的SQL是数据库最大的福祉. 一条很烂的SQL,可以搞瘫一 ...
- 【c++】【常用函数】
分割字符串:https://www.cnblogs.com/zealousness/p/9971709.html 字符串比较:https://www.cnblogs.com/zealousness/p ...
- Python并行编程(十):多线程性能评估
1.基本概念 GIL是CPython解释器引入的锁,GIL在解释器层面阻止了真正的并行运行.解释器在执行任何线程之前,必须等待当前正在运行的线程释放GIL,事实上,解释器会强迫想要运行的线程必须拿到G ...
- etcd: request cluster ID mismatch错误解决【只适用于新建etcd集群或无数据集群】
1.报错信息 Mar 29 05:45:31 xxx etcd: request cluster ID mismatch (got 414f8613693e2e2 want cdf818194e3a8 ...
- 【opencv入门篇】 10个程序快速上手opencv【上】
导言:本系列博客目的在于能够在vs快速上手opencv,理论知识涉及较少,大家有兴趣可以查阅其他博客深入了解相关的理论知识,本博客后续也会对图像方向的理论进一步分析,敬请期待:) PS:官方文档永远是 ...
- areas表-省市区
不全,缺少台湾省.香港.澳门:新疆重复了 /* Navicat MySQL Data Transfer Source Server : win7_local Source Server Version ...
- window7配置SQLserver 允许被远程连接
需要别人远程你的数据库,首先需要的是在一个局域网内,或者连接的是同一个路由器,接下来就是具体步骤: (一)首先是要检查SQLServer数据库服务器中是否允许远程链接.其具体操作为: (1)打开数据库 ...
- (转)VS中的路径宏 vc++中OutDir、ProjectDir、SolutionDir各种路径说明
$(RemoteMachine) 设置为“调试”属性页上“远程计算机”属性的值.有关更多信息,请参见更改用于 C/C++ 调试配置的项目设置. $(References) 以分号分隔的引用列表被添 ...
- #if defined(__cplusplus)
由于C++编译器需要支持函数的重载,会改变函数的名称,因此dll的导出函数通常是标准C定义的.这就使得C和C++的互相调用变得很常见.但是有时可能又会直接用C来调用,不想重新写代码,让标准C编写的dl ...