SpringBean生命周期-Version-v5.1.0.RELEASE
首先入口选定在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的生命周期的方法主要有两个,分别是populateBean
和initializeBean
。
首先进入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;
}
当populateBean
和initializeBean
方法走完并成功返回则说明该对象的属性注入和初始化方法调用,则会在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接口的实现类做相应处理 ->
调用BeanPostProcessor
的postProcessBeforeInitialization
->
调用InitializingBean
实现类的afterPropertiesSet
->
调用BeanPostProcessor
的postProcessAfterInitialization
->
通过DestructionAwareBeanPostProcessor
对destory-method
方法推断,解析 ->
通过lifecycleProcessor
调用Lifecycle
实现类的start
方法
----------------------------------容器成功创建---------------------------------------
通过lifecycleProcessor
调用Lifecycle
实现类的stop
方法
调用DisposableBean
的destroy
方法
SpringBean生命周期-Version-v5.1.0.RELEASE的更多相关文章
- 解决Maven 报 Return code is: 400 , ReasonPhrase:Repository version policy: SNAPSHOT does not allow version: 2.1.0.RELEASE. 的错误
最近在搭建公司的基础框架,业务需求用到elasticsearch,所以需要整合到基础框架里,供各业务线使用同时也便于管理,但在整合的过程中,出现了莫名的问题,同时maven的提示也不够明确. 我的版本 ...
- 深入源码理解SpringBean生命周期
概述 本文描述下Spring的实例化.初始化.销毁,整个SpringBean生命周期,聊一聊BeanPostProcessor的回调时机.Aware方法的回调时机.初始化方法的回调及其顺序.销毁方法的 ...
- 北京某大公司:SpringBean生命周期
<对线面试官>系列目前已经连载25篇啦!有深度风趣的系列! [对线面试官]Java注解 [对线面试官]Java泛型 [对线面试官] Java NIO [对线面试官]Java反射 & ...
- SpringBean生命周期
Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...
- SpringBean生命周期及作用域
bean作用域 在Bean容器启动会读取bean的xml配置文件,然后将xml中每个bean元素分别转换成BeanDefinition对象.在BeanDefinition对象中有scope 属性,就是 ...
- 回炉Spring--Bean生命周期及AOP
Spring容器: 在基于Spring的应用中,你的应用对象生存于Spring容器(container)中,Spring容器负责创建对象,装配它们,配置它们并管理它们的整个生命周期,从生存到死亡.(在 ...
- 进阶:spring-bean生命周期流程
Bean的生成过程 主要流程图 1. 生成BeanDefinition Spring启动的时候会进行扫描,会先调用org.springframework.context.annotation.Clas ...
- springbean 生命周期
springbean 和java对象得区别: 1.对象:任何符合java语法规则实例化出来的对象 2.springbean: 是spring对普通对象进行了封装为BeanDefinition,bean ...
- springBean生命周期----来自spring实战总结
1.Spring对bean进行实例化 2.Spring将值和bean的引用注入到bean对应的属性中(比如说注入到被依赖的bean的方法中或属性里) 3.如果bean实现了BeanNameAware接 ...
随机推荐
- kafka+zookeeper快速启动
vim zookeeper.sh #!/bin/bash /usr/local/zookeeper/bin/zkServer.sh restart /usr/local/zookeeper/con ...
- zookeeper的客户端常用操作
一,查看当前zookeeper的版本: [root@localhost conf]# echo stat|nc 127.0.0.1 2181 Zookeeper version: 3.5.6-c11b ...
- 天猫精灵对接2(OAuth 搭建)
根据 接入方式及流程 中的说明,可知,搭建过程中,我们需要自己整一个 OAuth 的授权平台,具体说明可以参考蟋蟀大哥的文章 ASP.NET WebApi OWIN 实现 OAuth 2.0 ,我的 ...
- 全宇宙首个.NET5+Vue.js前后端分离以及业务模块化快速开发框架【NetModular】发布~
最近.Net圈子很热闹啊,我也来凑凑,今天中午耗时长达半小时,把NetModular升级到了.NET5,详情查看分支https://github.com/iamoldli/NetModular/tre ...
- dubbo配置加载优先级
优先级从高到低: JVM 启动 -D 参数优先,这样可以使用户在部署和启动时进行参数重写,比如在启动时需改变协议的端口: XML 次之,如果在 XML 中有配置,则 dubbo.properties ...
- VirtualXposed结合justTrustMe 模块傻瓜式破解app没法抓包问题
一.首先就是按照这两个apk 声明仅供学习 justTrustMe 链接:https://pan.baidu.com/s/1av3oaez4y4n6a9C1I0VsAg 提取码:mjqg Virtua ...
- 初探RT-Thread系统在GD32E103x芯片上的使用,点亮LED灯
初探RT-Thread系统在GD32E103x芯片上的使用,点亮LED灯 前言 随着中美贸易战的加剧,很多公司越来越重视使用国产技术的重要性.使用国产技术,一方面可规避国外对技术的封锁造成产品核心 ...
- unordered_set
用哈希表实现的 https://blog.csdn.net/dream_you_to_life/article/details/46785741
- python的deque(双向)队列详解
首先 python的队列有很多种 Python标准库中包含了四种队列,分别是queue.Queue / asyncio.Queue / multiprocessing.Queue / collecti ...
- react-native中textInput在androidTV上的焦点处理(坑篇)
react-native中,开发androidTV输入框的焦点处理. 复述流程: 安卓TV上,无法通过上下左右键,以及遥控器的上下左右来获取输入框焦点. 原因: 脸书的锅,但没修,这里官方的说法,Te ...