Spring IoC 中的(Singleton)单例对象创建过程探索
前言
之前将spring framework 源码导入了idea,后来折腾调试了一下,于是研究了一下最简单的singleton对象在spring中是如何创建的。这里所谓的简单,就是指无属性注入,无复杂构造函数的对象。
测试代码
spring配置:
<bean id="userService" class="UserService" scope="singleton"></bean>
测试类:
public class UserService {
private final Log logger = LogFactory.getLog(getClass());
public UserService(){
logger.info("UserService created");
id = UUID.randomUUID().toString();
}
private String id;
public String getId(){
return id;
}
public String getUserName(){
return "xiaopanzi";
}
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.start();
testNormalSingleton(context);
}
private static void testCircleSingleton(ClassPathXmlApplicationContext context){
SingletonAService aService = context.getBean("aService",SingletonAService.class);
SingletonBService bService = context.getBean("bService",SingletonBService.class);
aService.getbService().print();
bService.getaService().print();
}
调试详情
首先在ApplicationContext 初始化过程,在 refresh 方法中会调用 finishBeanFactoryInitialization 方法,注释上也写的很明白:Instantiate all remaining (not-lazy-init) signletons。(初始化剩余的非懒加载的单例对象)。那么这里就是入口点。
然后在调用 beanFactory.preInstantiateSingletons().
后续调用链如下:
DefaultListBeanFactory.getBean(beanName)
AbstractBeanFactory.doGetBean(name,requiredType,args,typeCheckOnly)
AbstractAutowireCapableBeanFactory.createBean(String beanName,RootBeanDefinition mbd,Object[] args)
AbstractAutowireCapableBeanFactory.doCreateBean(String beanName,RootBeanDefinition mbd,Object[] args)
AbstractAutowireCapableBeanFactory.instantiateBean(final String beanName, final RootBeanDefinition mbd)
getInstantiationStrategy().instantiate(mbd, beanName, parent); (this.instantiationStrategy=CglibSubclassingInstantiationStrategy)
SimpleInstantiationStrategy.instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
BeanUtils.instantiateClass(Constructor<T> ctor, Object... args)
通过上述代码调用链我们可以看出,最终的示例创建是由 BeanUtils.instantiateClass 方法完成的,也就是这个方法:

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
到此为止单例就创建完毕了。但是创建完成之后,还有后续的处理。
DefaultSingletonBeanRegistry.addSingletonFactory(String beanName,ObjectFactory<?> singletonFactory);
也就是将该示例放入到 singletonObjects 中,作为缓存方便后续取值。
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
当我们在次调用getBean的时候,那么在 DefaultSingletonBeanRegistry.getSingleton 方法中直接从 singletonObjects 中获取即可。
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
总结
上述内容记录的很少,基本就是一个轮廓的记录,要真正理解详情内容,还得自己去慢慢调试啊!!!
Spring IoC 中的(Singleton)单例对象创建过程探索的更多相关文章
- Spring IOC(三)单例 bean 的注册管理
Spring IOC(三)单例 bean 的注册管理 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 在 Spring 中 ...
- Singleton单例对象的使用
namespace www{ public abstract class SingletonManager<T> : ISingletonManager where T : class, ...
- Spring IOC 容器源码分析 - 创建单例 bean 的过程
1. 简介 在上一篇文章中,我比较详细的分析了获取 bean 的方法,也就是getBean(String)的实现逻辑.对于已实例化好的单例 bean,getBean(String) 方法并不会再一次去 ...
- 不允许在单例对象中创建Srping容器
spring.net在使用的时候,不允许在单例对象中创建Srping容器 需要将实例化模式转为单例singleton=“false”
- 从别人写的 Object-C 中 Singleton (单例) 模式 中的一些理解--备
关于 面向对象的设计模式 对于面向对象的设计模式,想必大家并不陌生吧. 纵观23种设计模式中,数单例模式(Singleton)和工厂模式(Factory Method)最为熟悉和基础吧.当然,本文总结 ...
- 【cocos2d-js官方文档】二十五、Cocos2d-JS v3.0中的单例对象
为何将单例模式移除 在Cocos2d-JS v3.0之前.全部API差点儿都是从Cocos2d-x中移植过来的,这是Cocos2d生态圈统一性的重要一环.可惜的是,这样的统一性也在非常大程度上限制了C ...
- atitit.guice3 绑定方式打总结生成非单例对象toInstance toProvider区别 v2 pb29
atitit.guice3 绑定方式打总结生成非单例对象toInstance toProvider区别 v2 pb29 1. 三 绑定方式的介绍1 2. To接口,链式绑定,用的最多的1 3. toC ...
- OC中两种单例实现方式
OC中两种单例实现方式 写在前面 前两天探索了一下C++ 的单例,领悟深刻了许多.今天来看看OC中的单例又是怎么回事.查看相关资料,发现在OC中一般有两种实现单例的方式,一种方式是跟C++ 中类似的常 ...
- 【Cocos2d-X游戏实战开发】捕鱼达人之单例对象的设计(二)
本系列学习教程使用的是cocos2d-x-2.1.4(最新版为cocos2d-x-2.1.5) 博主发现前两个系列的学习教程被严重抄袭,在这里呼吁大家请尊重开发者的劳动成果, 转载的时候请务必注 ...
随机推荐
- C# 连接Oracle,进行查询,插入操作
注:OracleConnection和OracleCommand已被标注为[弃用的],可以使用System.Data.OleDb.OleDbConnection代替OracleCOnnection,使 ...
- maven <resources>标签
<build> <finalName>com_dubbo_config</finalName> <resources> <resource> ...
- IDEA创建Maven项目和子模块
一.新建Project a. 新建项目,点击Create New Project b. 选择使用maven来新建项目 选择新建Maven模块(对IDEA来说是项目) 如果Project SDK那里没有 ...
- 六 Selector
选择器是java NIO中能够检测一到多个NIO通道(Channel),并能知晓是否为诸如读写时间做好准备的组件.这样,一个单独的线程可以管理多个channel,从而管理多个网络连接 为什么用Sele ...
- 10.31NOIP模拟赛解题报告
心路历程 预计得分:\(100 +100 +80\) 实际得分:\(30 + 100 + 80\) 天天挂分..感觉我noip要凉.. T1不难,但是太坑了 T2不难 T3不难,但是在小机房考试脑子都 ...
- 浮动的补充丶文本和字体属性丶background丶定位
一丶浮动的补充 浮动的特性: 1. 浮动的元素脱标 2.浮动的元素互相贴靠 3.浮动的元素有"字围"效果 4.浮动的元素有收缩的效果 前提是标准文档流,margin的垂直方向会出现 ...
- Java入门到精通——调错篇之Astah Community打开报需要jre1.7运行环境
1.问题概述 Astah Community安装完以后点击运行Astah Community的时候报此应用需要jdk1.7如下图 但是我的电脑在D盘装了jdk1.8了为什么这个软件为什 ...
- freebsd默认不是gcc构建
xunsearch在freebsd上死活装不上,用gcc编译通过. freebsd默认不是gcc编译工程,所以下个gcc ./configure CC=gcc48 编译. 觉得clang编译器不可能有 ...
- How to Build MySQL from Source Code on Windows & compile MySQL on win7+vs2010
Not counting obtaining the source code, and once you have the prerequisites satisfied, [Windows] use ...
- 常见的浏览器兼容性问题与解决方案——CSS篇
1.不同的浏览器的标签默认的外补丁和内补丁不同 问题症状:随便写几个标签,不加样式控制的情况下,各自的margin和padding差异较大. 碰到频率:100% 解决方案:初始化CSS的默认样式,*{ ...