Spring Boot源码(六):Bean的创建详解
继续之前的项目:
People加上无参构造方法:
@Component
public class People {
// private User user;
public People(){
System.out.println("create People");
}
}
在refresh()方法中,打上断点:

在此方法之前,People对象都没有被创建(没有调用构造方法)
关注此方法:
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
} // Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
} // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
} // Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
此方法的注释也说明了。这里只会实例化,不是懒加载,是单例的bean。

执行此方法后控制台才输出:
create People
这说明对象的创建是在此方法(DefaultListableBeanFactory类)中:
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
} // Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
} // Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
DefaultListableBeanFactory可以说是spring的容器,里面有各种map属性,例如beanDefinitionMap,beanDefinitionNames:

这里我们使用条件断点(右击断点),因为我们只关注自己的People类,而beanDefinitionMap中有spring自己的类,一个一个遍历断点太麻烦:

遍历此map,用beanName(key)拿到对应的beanDefinition(value);
这里拿到了People的BeanDefinition对象,可以看到spring默认的scope就是singleton,不是懒加载

判断 不为抽象类,是单例,不是懒加载

再判断是否为Factorybean,很显然我们的People不是:

直接进入else:


首先去拿有没有对象,如果没有再创建。
getSingleton()是一个比较重要的方法。
@Nullable
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;
}

isSingletonCurrentlyIncreation()这个方法这里为false,大概意思当前是否是创建对象的过程。主要可以去解决循环依赖,之后再说,详见Spring Boot源码(七):循环依赖。

上面又调用了一次getSingleton方法,还用了lambda表达式,具体创建bean就是createBean()方法了。
Spring Boot源码(六):Bean的创建详解的更多相关文章
- Spring IoC源码解析——Bean的创建和初始化
Spring介绍 Spring(http://spring.io/)是一个轻量级的Java 开发框架,同时也是轻量级的IoC和AOP的容器框架,主要是针对JavaBean的生命周期进行管理的轻量级容器 ...
- 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享
写在前面的话&&About me 网上写spring的文章多如牛毛,为什么还要写呢,因为,很简单,那是人家写的:网上都鼓励你不要造轮子,为什么你还要造呢,因为,那不是你造的. 我不是要 ...
- 曹工说Spring Boot源码(2)-- Bean Definition到底是什么,咱们对着接口,逐个方法讲解
写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 正 ...
- 曹工说Spring Boot源码(6)-- Spring怎么从xml文件里解析bean的
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- 曹工说Spring Boot源码(19)-- Spring 带给我们的工具利器,创建代理不用愁(ProxyFactory)
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- Spring Boot源码(四):Bean装配
为了演示Spring中对象是如何创建并放到spring容器中,这里新建一个maven项目: 其中pom.xm文件中只引入了一个依赖: <dependencies> <dependen ...
- 曹工说Spring Boot源码(3)-- 手动注册Bean Definition不比游戏好玩吗,我们来试一下
写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 大 ...
- 曹工说Spring Boot源码(4)-- 我是怎么自定义ApplicationContext,从json文件读取bean definition的?
写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 大 ...
- 曹工说Spring Boot源码(5)-- 怎么从properties文件读取bean
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
随机推荐
- FFMPEG学习----使用SDL播放YUV数据
命令行下配置: G:\Coding\Video\SDL\proj>tree /F 文件夹 PATH 列表 卷序列号为 0FD5-0CC8 G:. │ sdl.cpp │ SDL2.dll │ S ...
- HDU_2446_打表
http://acm.hdu.edu.cn/showproblem.php?pid=2446 打表,二分查找,注意查找最后的判断. #include<cstdio> #define N 2 ...
- Codevs 1205 单词反转(Vector以及如何输出string)
题意:倒序输出句子中的单词 代码: #include<cstdio> #include<iostream> #include<string> #include< ...
- DBA常用SQL之DDL生成语句-2
------数据迁移常用SQL SELECT 'DROP USER '||u.username ||' CASCADE;' AS dropstrs FROM DBA_USERS U where u.u ...
- Scala 学习(10)之「集合 」
数组 定长数组 Array:采用()访问,而不是[],下标从 0 开始. val array1 = new Array[String](5) //创建数组 println(array1) //返回数组 ...
- OsgEearh 中的 FeatureEditor的实现原理
先来看看FeatureEditor的用法: const osgEarth::SpatialReference* mapSRS = mapNode->getMapSRS(); osgEarth:: ...
- html标签学习入门 随笔
Html学习入门 随笔1: HTML 标题 HTML 标题(Heading)是通过 <h1> - <h6> 等标签进行定义的. 标题仅用于标题文本 不应该被使用在加粗字 ...
- 图像数组运算相关问题(nan/inf)
新年第一更!祝愿新的一年技术长足进步哈! 最近在用sklearn的回归分析模型拟合预测遥感图像,遇到了一些问题,好在一一解决,现在总结一下. 1.首先输入sklearn的数据必须reshape(-1, ...
- 详解SkipList跳跃链表【含代码】
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天继续介绍分布式系统当中常用的数据结构,今天要介绍的数据结构非常了不起,和之前介绍的布隆过滤器一样,是一个功能强大原理简单的数据结构.并且 ...
- Python——格式输出,基本数据
一.问题点(有待解决) 1.Python中只有浮点数,20和20.0是否一样? from decimal import Decimal a = Decimal('1.3') round() 参考文章 ...