上节探讨了Spring IOC容器中getBean方法,下面我们将自行编写测试用例,深入跟踪分析bean对象创建过程。
测试环境创建
测试示例代码如下:
package org.springframework.context.mytests;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextTest {
@Test
public void testApplicationContext() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("numbers: " + applicationContext.getBeanDefinitionCount());
((Worker)applicationContext.getBean("worker")).work();
}
}
应用ClassPathXmlApplicationContext加载解析xml文件,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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="worker" class="org.springframework.context.mytests.Worker"></bean>
</beans>
bean Worker代码如下:
package org.springframework.context.mytests;
public class Worker {
public void work(){
System.out.println("I am working");
}
}
在IDE中对测试文件打断点,进入Debug模式,一步一步跟随程序跟踪bean创建过程。
源码跟踪
跟踪断点,进入ClassPathXmlApplicationContext源码,如下所示:
package org.springframework.context.support;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
......
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
......
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
......
}
ClassPathXmlApplicationContex中都是构造器方法,表明加载解析xml文件的操作都是在实例化阶段完成的。以上是部分源码片段,在本测试中,调用第一个构造器初始化,但其实质是调用第二个构造器。从源码可以发现,第二个构造器实际上完成了两个主要功能:
-
setConfigLocations(configLocations)
,设置应用上下文的配置文件路径,如果没有设置,便会使用默认路径 -
refresh()
,IOC容器初始化入口
通过查找定位发现:setConfigLocations(configLocations)
是继承于AbstractRefreshableConfigApplicationContext抽象类,其源码如下:
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++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
可以看到setConfigLocations方法获取定位信息首先需要调用resolvePath方法对路径进行预处理。
refresh方法是继承于AbstractApplicationContext抽象类,是在接口ConfigurableApplicationContext中定义的。其在抽象类中源码如下:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
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.
destroyBeans();
// Reset 'active' flag.
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...
resetCommonCaches();
}
}
}
refresh方法大致描述了Spring IOC容器的初始化过程,第一步prepareRefresh
主要是做一些准备工作,如准备应用环境、设置启动时间、设置属性源初始化标志等。重点看第二步ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
,这一步是获取更新后的子类Bean工厂。其源码如下:
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
其内部有两个方法refreshBeanFactory()
和getBeanFactory()
,这两个方法均为抽象方法,如下所示:
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
查找子类发现,这两个方法均在子类AbstractRefreshableApplicationContext中实现,该类仍然是抽象类。先来看refreshBeanFactory方法实现:
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
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,若存在则直接销毁原BeanFactory,先销毁工厂中的Beans,再关闭工bean厂。之后创建新的Bean工厂,其方法为createBeanFactory
,如下所示:
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
从函数返回值可以看出,重新创建的Bean工厂是默认的bean工厂DefaultListableBeanFactory
类型。创建完新的bean工厂后便会根据上下文进行初始化(customizeBeanFactory),加载bean定义(loadBeanDefinitions)。其中,loadBeanDefinitions为抽象方法,如下所示:
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException;
该方法具体实现在AbstractXmlApplicationContext类中,该类仍然是一个抽象类,实现如下:
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
阅读源码发现,方法内部是采用XmlBeanDefinitionReader来读取加载bean对象。通过追踪源码,发现XmlBeanDefinitionReader最终调用loadBeanDefinitions方法来读取加载bean,具体实现如下:
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();
}
}
}
到此,应该明白了IOC容器初始化bean工厂、加载bean对象的大致过程了。现在回头再来看obtainFreshBeanFactory方法中的另一个方法getBeanFactory方法。该方法在子类AbstractRefreshableApplicationContext中实现就相对简单写,如下所示:
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}
到此为止,Spring IOC容器加载机制探讨基本上告一段落了。通过对源码分析,对Spring IOC机制能有一个大致的了解:1、解析、定位、加载xml配置文件;2、提取配置文件内容;3、新建bean工厂;4、创建Bean定义,并放入map中存储。通过追踪源码,也深刻体会到了spring对设计模式的应用。
下一节将进入对Spring另一大杀器的探讨,Spring-AOP。
Spring IOC容器分析(4) -- bean创建获取完整流程的更多相关文章
-
Spring IOC容器分析(2) -- BeanDefinition
上文对Spring IOC容器的核心BeanFactory接口分析发现:在默认Bean工厂DefaultListableBeanFactory中对象不是以Object形成存储,而是以BeanDefin ...
-
Spring IOC容器分析(3) -- DefaultListableBeanFactory
上一节介绍了封装bean对象的BeanDefinition接口.从前面小结对BeanFactory的介绍中,我们知道bean对象是存储在map中,通过调用getBean方法可以得到bean对象.在接口 ...
-
Spring学习--实现 FactoryBean 接口在 Spring IOC 容器中配置 Bean
Spring 中有两种类型的 bean , 一种是普通的 bean , 另一种是工厂 bean , 即 FactroyBean. 工厂 bean 跟普通 bean 不同 , 其返回的对象不是指定类的一 ...
-
Spring IOC容器分析(1) -- BeanFactory
搭建好源码阅读环境后,就可以慢慢走进Spring殿堂了.IOC是Inversion of Control的缩写,控制反转的意思.很多人可能都知道IOC是spring的核心,将对象的创建初始化等权限交由 ...
-
Spring IOC容器中注入bean
一.基于schema格式的注入 1.基本的注入方式 (属性注入方式) 根据setXxx()方法进行依赖注入,Spring只会检查是否有setter方法,是否有对应的属性不做要求 <bean id ...
-
Spring源码分析之Bean的加载流程
spring版本为4.3.6.RELEASE 不管是xml方式配置bean还是基于注解的形式,最终都会调用AbstractApplicationContext的refresh方法: @Override ...
-
Spring IoC 容器和 bean 对象
程序的耦合性: 耦合性(Coupling),又叫耦合度,是对模块间关联程度的度量.耦合的强弱取决于模块间接口的复杂性.调用模块的方式以及通过界面传送数据的多少.模块间的耦合度是指模块之间的依赖关系,包 ...
-
纯注解快速使用spring IOC容器
使用spring的ioc容器实现对bean的管理与基本的依赖注入是再经典的应用了.基础使用不在详述. 这里主要介绍下使用注解实现零配置的spring容器.我相信你也会更喜欢使用这种方式.Spring ...
-
Spring ——Spring IoC容器详解(图示)
1.1 Spring IoC容器 从昨天的例子当中我们已经知道spring IoC容器的作用,它可以容纳我们所开发的各种Bean.并且我们可以从中获取各种发布在Spring IoC容器里的Bean,并 ...
随机推荐
-
WPF捕捉Windows关机事件
private const int SC_SCREENSAVE = 0xF140; private const int WM_QUERYENDSESSION = 0x0011; private boo ...
-
php--在apache上配制rewrite重写
配置步骤: 第一步:找到apache的配置文件httpd.conf(文件在conf目录下) 第二步:你首先必须得让服务器支持mod_rewrite,如果你使用的是虚拟主机,请事先询问你的主机提供商. ...
-
【译】在JavaScript中{}+{}的结果是什么?
原文链接:What is {} + {} in JavaScript? 最近,Gary Bernhardt在一个名为'Wat'的闪电演讲中提到了一些有趣的JavaScript技巧.当你把一个objec ...
-
js经验1
1. input 获得焦点 focus(); 2.获得文档的的title _title = document.title; 3.定时检查删除dom定时器 var deleteDomInterval ...
-
用javascript向一个网页连接接口发送请求,并接收该接口返回的json串
一般前端与后端的互交都是通过json字符串来互交的,我的理解就是与网页接口的来回数据传递采用的数据结构就是json.一般是这样. 比如后端的代码是这样的: @RequestMapping(value ...
-
C# 基础知识 (三).主子对话框数值传递
在C# winform编程中,我们经常会遇到不同窗口间需要传递数值的问题.比如数据库的应用,主窗口填写内容num1,点击按钮,在弹出的子窗口显示对应num1值;或者在子窗口填写新注册用户名信息,在主窗 ...
-
[睡前灵感and发散思维]由一个简单的数组比较问题而想到的
前言 据说,一只优秀的程序猿往往会有这样的经历,白天遇到一个绞尽脑汁也无法解决的问题,晚上睡了后,半夜在梦中会灵感涌现,立马起床,打开电脑,一气呵成.第二天如果不看注释,完全不知道自己找到了如此巧妙地 ...
-
【3D美术教程】手雷(传统与PBR流程)
转自:https://www.sohu.com/a/156489635_718614 随着最新的次时代技术PBR流程的普及,越来越多的公司由传统流程转向了PBR流程,主要原因在于PBR材质不仅效果上更 ...
-
Linux下编译安装Lnmp
1.安装nginx 下载链接http://nginx.org/en/download.html (1)下载,解压 wget http://nginx.org/download/nginx-1.15.8 ...
-
vi 命令 行首、行尾
vim 跳到行首 : 数字 0 vim跳到行位 : $ [Shift + 4]