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) 博主发现前两个系列的学习教程被严重抄袭,在这里呼吁大家请尊重开发者的劳动成果, 转载的时候请务必注 ...
随机推荐
- MySql 双实例安装
1.官网下载压缩包 https://dev.mysql.com/downloads/mysql/ 2.解压到D盘 3.修改my.ini 文件 [mysql] # 设置mysql客户端默认字符集 def ...
- 十、cent OS开启APR模式报错:configure: error: Found APR 1.3.9. You need version 1.4.3 or newer installed
错误内容显示APR的版本过低,需要新版本 到http://apr.apache.org/download.cgi#apr1这个地址下载所需要的包apr-1.4.5.tar.gz apr-iconv-1 ...
- explode 把字符串打散为数组
// 显示的字段列表 $smarty->assign('field_show', explode(',',$list_name)); explode(separator,string,limit ...
- Spring Security +Oauth2 +Spring boot 动态定义权限
Oauth2介绍:Oauth2是为用户资源的授权定义了一个安全.开放及简单的标准,第三方无需知道用户的账号及密码,就可获取到用户的授权信息,并且这是安全的. 简单的来说,当用户登陆网站的时候,需要账号 ...
- CF Dima and Salad 01背包
C. Dima and Salad time limit per test 1 second memory limit per test 256 megabytes input standard in ...
- MyBaits_查询缓存02_Ehcache二级缓存
一.Ehcache二级缓存的开启 导入jar(https://github.com/mybatis/ehcache-cache/releases) <cache type="org.m ...
- lintcode 题目记录2
判断字符串是否是互为置换,类似 替换字符串之类的遍历就行了.. class Solution: # @param {string} A a string # @param {string} B a s ...
- js-JavaScript的简介
JavaScript的简介 * 是基于对象和事件驱动的语言,应用于客户端 - 基于对象: ** 提供好了很多对象,可以直接拿过来使用 - 事件驱动: ** HTML做网站静态效果,JavaScript ...
- 谈谈HTML5中的history.pushSate方法,弥补ajax导致浏览器前进后退无效的问题
移动端为了减少页面请求,有时候需要通过单页面做成多页面的效果,最近有这么个需求,表单填完后执行第一步,然后执行第二步,第二步执行完后再执行第三步,每一步都要保留之前的数据.这种情况用单页面实现再合适不 ...
- Goodbye Bingshen
在uoj上打的第二场比赛......还凑合(卧槽C题80分没了QAQ 第一次接触交互题还挺好玩的哈哈 可能是人比较多吧.....rating涨了不少...... 现在我rating正好比lrd高1哈哈 ...