首先入口选定在org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons这个方法中

public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("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) {
//复制一份BeanDefinition对象并返回(可能是为了将各种BeanDefinition实现类转换成RootBeanDefinition统一处理)
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象,非懒加载并且为单例
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//FatoryBean实现类则走进入这个if
//本次不做分析
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 {
//非FactoryBean实现类则走这个方法
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();
}
}
}
}

从这个方法中可以看出Spring实例化对象的条件有三个。分别是非抽象,非懒加载并且为单例。

并且实例化完成后还会从beanFactory中获取所有的SmartInitializingSingleton实现类并调用其afterSingletonsInstantiated方法。

从getBean()方法追进去则会走到org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean方法中

	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { //剔除name前所有的“&”,并返回
final String beanName = transformedBeanName(name);
Object bean; // Eagerly check singleton cache for manually registered singletons.
//解决对象之间循环创建的重要一环(第一次调用getSingleton)
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
...
...省略部分 if (!typeCheckOnly) {
//将该beanName放入alreadyCreated中,标识已经创建
markBeanAsCreated(beanName);
} try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//确保BeanDefinition是非抽象的
checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
} // Create bean instance.
if (mbd.isSingleton()) {
//第二次调用getSingleton的重载方法,对象的具体创建则体现在createBean()方法中
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
...
...省略非单例bean逻辑
} } // Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
...
...默认requiredType为null,所以该段落及并不会进入
}
return (T) bean;
}

从这个方法首先对beanName做了一定的处理,剔除了头部的所有“&”符号,分别调用了两次getSingleton的重载方法,其中对象的创建在第二个getSingleton方法的lamba表达式的createBean方法中

	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd; //确保mbd中有Class,如果没有则重新实例化一个RootBeanDefinition并装载该Class对象
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
...
...省略部分代码
try {
//给BeanPostProcessors一个返回代理而不是目标bean实例的机会。
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
} try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

在这个方法中并没有什么特别的逻辑,所以直接跟进doCreateBean方法中

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException { // Instantiate the bean.
BeanWrapper instanceWrapper = null;
//和FactoryBean有关逻辑,忽略
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建一个该对象的包装类,该包装类中持有该对象(这个方法中包含构造器推断)
//发现第一处BeanPostProcessor->SmartInstantiationAwareBeanPostProcessor.
//determineCandidateConstructors
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//此时对象已被推断出来的构造方法创建创建
final Object bean = instanceWrapper.getWrappedInstance();
//获取该对象的Class
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
//表示该对象已被处理,或正在被处理
mbd.resolvedTargetType = beanType;
} // Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//发现第二处BeanPostProcessor->MergedBeanDefinitionPostProcessor.
//postProcessMergedBeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
//默认this.allowCircularReferences为true
//与org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean中第一次调用的
//getSingleton相互呼应(此时放入的对象还未属性注入,仅仅是通过构造方法创建而已)
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
//属性注入
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
} if (earlySingletonExposure) {
//按照常规流程此时该对象并未放入singletonObjects中,并且,第二参数为false,所以为null
//并不会进入if
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
...
...省略
} // Register bean as disposable.
try {
//发现第七处BeanPostProcessor->DestructionAwareBeanPostProcessor.
//requiresDestruction
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
} return exposedObject;
}

这个方法中涉及到bean的生命周期的方法主要有两个,分别是populateBeaninitializeBean

首先进入populateBean一探究竟。

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...
...省略无关代码
boolean continueWithPropertyPopulation = true; //发现第三处BeanPostProcessor->InstantiationAwareBeanPostProcessor.
//postProcessAfterInstantiation
//默认返回true,若该PostProcessor处理结果为false则直接return,不做后续处理
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//分别对应自动装配中ByName和ByType
//https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-autowire官方文档这一章有做介绍
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
} boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//第四处调用BeanPostProcessor->InstantiationAwareBeanPostProcessor.
//postProcessProperties(在这个AutowiredAnnotationBeanPostProcessor中处理@autowired注解)
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
} if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

接下来是initializeBean方法

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//若该对象分别是BeanNameAware,BeanClassLoaderAware,BeanFactoryAware的实现类
//则调用相对应的方法,向该对象中注入所需属性
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//第五处调用BeanPostProcessor->postProcessBeforeInitialization
//InitDestroyAnnotationBeanPostProcessor处理@PostConstruct注解
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
//如果该对象是InitializingBean的实现类,则调用afterPropertiesSet方法,或调用自定义的初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//第六处调用BeanPostProcessor->postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
} return wrappedBean;
}

populateBeaninitializeBean方法走完并成功返回则说明该对象的属性注入和初始化方法调用,则会在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)方法中finally语句块调用addSingleton方法将该对象和BeanName注册进singletonObjects中。至此该对象成为spring容器中的bean。

总结:

通过SmartInstantiationAwareBeanPostProcessor推断构造方法并实例化符合要求的对象 ->

通过MergedBeanDefinitionPostProcessor对已被merge的对象做后置处理(个人理解为对BeanDefinition的解析) ->

通过InstantiationAwareBeanPostProcessor对该对象属性注入 ->

对Aware接口的实现类做相应处理 ->

调用BeanPostProcessorpostProcessBeforeInitialization ->

调用InitializingBean实现类的afterPropertiesSet ->

调用BeanPostProcessorpostProcessAfterInitialization ->

通过DestructionAwareBeanPostProcessordestory-method方法推断,解析 ->

通过lifecycleProcessor调用Lifecycle实现类的start方法

----------------------------------容器成功创建---------------------------------------

通过lifecycleProcessor调用Lifecycle实现类的stop方法

调用DisposableBeandestroy方法

SpringBean生命周期-Version-v5.1.0.RELEASE的更多相关文章

  1. 解决Maven 报 Return code is: 400 , ReasonPhrase:Repository version policy: SNAPSHOT does not allow version: 2.1.0.RELEASE. 的错误

    最近在搭建公司的基础框架,业务需求用到elasticsearch,所以需要整合到基础框架里,供各业务线使用同时也便于管理,但在整合的过程中,出现了莫名的问题,同时maven的提示也不够明确. 我的版本 ...

  2. 深入源码理解SpringBean生命周期

    概述 本文描述下Spring的实例化.初始化.销毁,整个SpringBean生命周期,聊一聊BeanPostProcessor的回调时机.Aware方法的回调时机.初始化方法的回调及其顺序.销毁方法的 ...

  3. 北京某大公司:SpringBean生命周期

    <对线面试官>系列目前已经连载25篇啦!有深度风趣的系列! [对线面试官]Java注解 [对线面试官]Java泛型 [对线面试官] Java NIO [对线面试官]Java反射 & ...

  4. SpringBean生命周期

    Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...

  5. SpringBean生命周期及作用域

    bean作用域 在Bean容器启动会读取bean的xml配置文件,然后将xml中每个bean元素分别转换成BeanDefinition对象.在BeanDefinition对象中有scope 属性,就是 ...

  6. 回炉Spring--Bean生命周期及AOP

    Spring容器: 在基于Spring的应用中,你的应用对象生存于Spring容器(container)中,Spring容器负责创建对象,装配它们,配置它们并管理它们的整个生命周期,从生存到死亡.(在 ...

  7. 进阶:spring-bean生命周期流程

    Bean的生成过程 主要流程图 1. 生成BeanDefinition Spring启动的时候会进行扫描,会先调用org.springframework.context.annotation.Clas ...

  8. springbean 生命周期

    springbean 和java对象得区别: 1.对象:任何符合java语法规则实例化出来的对象 2.springbean: 是spring对普通对象进行了封装为BeanDefinition,bean ...

  9. springBean生命周期----来自spring实战总结

    1.Spring对bean进行实例化 2.Spring将值和bean的引用注入到bean对应的属性中(比如说注入到被依赖的bean的方法中或属性里) 3.如果bean实现了BeanNameAware接 ...

随机推荐

  1. 在 Istio 中实现 Redis 集群的数据分片、读写分离和流量镜像

    Redis 是一个高性能的 key-value 存储系统,被广泛用于微服务架构中.如果我们想要使用 Redis 集群模式提供的高级特性,则需要对客户端代码进行改动,这带来了应用升级和维护的一些困难.利 ...

  2. 1. Deep Q-Learning

    传统的强化学习算法具有很强的决策能力,但难以用于高维空间任务中,需要结合深度学习的高感知能力,因此延展出深度强化学习,最经典的就是DQN(Deep Q-Learning). DQN 2013 DQN的 ...

  3. 全球首个优秀的华人.net微服务框架 作者:百大僧

    话不多说,直接上地址 https://gitee.com/shoubashou/NetCoreMicroService,目标斩获10000star, 通往牛逼的路上,风景差得让人只说脏话. 是全球首个 ...

  4. webpack5文档解析(下)

    声明:所有的文章demo都在我的仓库里 代码分离 代码分离的有点在于: 切割代码,生成不同的打包文件,按需加载这些文件. 每个bundle的体积更小 控制外部资源的加载顺序 常用的方法有: 入口起点: ...

  5. unordered_set

    用哈希表实现的 https://blog.csdn.net/dream_you_to_life/article/details/46785741

  6. E. Almost Regular Bracket Sequence 解析(思維)

    Codeforce 1095 E. Almost Regular Bracket Sequence 解析(思維) 今天我們來看看CF1095E 題目連結 題目 給你一個括號序列,求有幾個字元改括號方向 ...

  7. pandas dataframe 时间字段 diff 函数

    pandas pandas 是数据处理的利器,非常方便进行表格数据处理,用过的人应该都很清楚,没接触的可以自行查阅pandas 官网. 需求介绍 最近在使用 pandas 的过程中碰到一个问题,需要计 ...

  8. python 作业 日报模板输出

    1 #!/usr/bin/env python 2 # coding: utf-8 3 4 import numpy as np 5 import pandas as pd 6 7 path='C:/ ...

  9. elk部署(实战一)

    项目介绍: 系统:redhat7.6 软件:es+logstash+kibana  6.1 IP+主机名 192.168.0.10    elk1 192.168.0.10    elk2 192.1 ...

  10. docker部署redis主从和哨兵

    docker部署redis主从和哨兵 原文地址:https://www.jianshu.com/p/72ee9568c8ea 1主2从3哨兵 一.前期准备工作 1.电脑装有docker 2.假设本地i ...