先来一张概图来展示生命周期:
个人觉得spring bean的生命周期的是建立在各种扩展点上的:
1.BeanPostProcessor
2.InitializingBean
3.DisposableBean
4.BeanNameAware
5.BeanClassLoaderAware
6.BeanFactoryAware
下面来记录下学习过程:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
bean的实例以及初始化实在:finishBeanFactoryInitialization(beanFactory) 处开始的,接着到:
beanFactory.preInstantiateSingletons(),spring的默认容器是:DefaultListableBeanFactory,
来到 preInstantiateSingletons方法:
循环 beanDefinitionNames 对象(invokeBeanFactoryPostProcessors(beanFactory)时加载定义创建了对应的beanDefinition) ,spring在此处做了判断:单例的,非懒加载的以及非抽象的对象,中间还区分了FactoryBean对象,但是不管怎么样,获取spring管理的bean对象时肯定是通过getBean的方式的,所以可以忽略,直接看getBean(beanName) , 到 doGetBean:
Object sharedInstance = getSingleton(beanName);
此处开始了非常重要的三级缓存机制,spring创建bean以及属性注入采取了递归+缓存标志对象的方式来解决的;
singletonFactories----》earlySingletonObjects—》singletonObjects + singletonsCurrentlyInCreation
singletonFactories:单例缓存bean对象工厂类,主要是负责创建对应的bean实例
earlySingletonObjects:单例缓存实例未初始化的对象
singletonObjects :单例缓存实例初始化好的对象
singletonsCurrentlyInCreation :标志已经实例化的bean对象,未初始化的对象
此处代码非常关键,解决循环依赖的重要一环:bean创建时第一次进入到次数的时候,单例缓存实例初始化对象 singletonObjects 以及 singletonsCurrentlyInCreation 肯定不包含此对象的(但是如果在循环依赖的时候,由于相互依赖,singletonObjects 不存在,但是 singletonsCurrentlyInCreation 存在,而 singletonFactories 在实例化实例化的依赖bean的时候就已经创建,所以必定存在,返回一个bean(未初始化),这样就解决了循环依赖的问题;)返回null ,接着检查该类的beanDefinition是否配置完全,略过,到:
此处到可getSingleton的重载方法,注意到这个createBean,待会用到,
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
这个方法非常关键:
在这里添加到 singletonsCurrentlyInCreation 里面,标识开始实例化但是没有初始化,接着到:
singletonObject = singletonFactory.getObject(); 这里调用到了刚刚的 createBean 方法,到doCreateBean,中间调用了:instanceWrapper = createBeanInstance(beanName, mbd, args);
这里就是通过 AbstractAutowireCapableBeanFactory 来获取对应的构造器 clazz.getDeclaredConstructor(),最终调用:
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent) 来返回一个实例化好的bean包装类:
此处已经实例化好了bean对象,接着:
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName) 此处开始了
扩展接口 MergedBeanDefinitionPostProcessor的
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName); 看形参可以知道此处可以修改bean 的定义,接着到:
调用:addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
此处加载进 singletonFactories 里面去,后期可以通过其对应的工厂类对象获取对应的bean,接着到了 populateBean(beanName, mbd, instanceWrapper); ,
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
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);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
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();
}
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);
}
}
这里首先检查是否有属性,没有直接return;
接着又开始了 InstantiationAwareBeanPostProcessor 的扩展点,没搞懂,略过;
获取所有属性,归类设定值得方式set与Autowire;接着又到了 InstantiationAwareBeanPostProcessor ,这里主要是利用 postProcessProperties 这个方法,我们主要看关键的:AutowiredAnnotationBeanPostProcessor 来,
可以看出这有对应的处理器,AutowiredAnnotationBeanPostProcessor 找出对应字段,判断类型,如果是对象的话,则通过调用 beanFactory.doResolveDependency 来处理,最终调用了 getBean 方法,递归开始了,首先通过 getSingleton 来获取,单例缓存实力初始化对象池以及标志池肯定没有,返回null,接着到重载的 getSingleton 方法,调用 beforeSingletonCreation 来存储对应的要创建的beanName, 结合通过 singletonFactory.getObject(); 进入到 crerateBean 方法 ,获取对应的构造器,
调用 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); 方法反射获取对象,接着包装返回,接着提供修改bean定义的实现 BBP , 结合调用 addSingletonFactory ,将单当前的 bean工厂类存储起来,接着开始了属性注入重复上面的逻辑;
重点来了:如果有循环依赖的话,则最终这么走:
此处对应了一开始说的在每一次创建对象时候,都必须判断三个类:
singletonFactories----》earlySingletonObjects—》singletonObjects + singletonsCurrentlyInCreation
singletonFactories:单例缓存bean对象工厂类,主要是负责创建对应的bean实例
earlySingletonObjects:单例缓存实例未初始化的对象 (没搞懂怎么用)
singletonObjects :单例缓存实例初始化好的对象
singletonsCurrentlyInCreation :标志已经实例化的bean对象,未初始化的对象,A依赖B,B依赖A,在创建A后属性注入B,B创建属性注入A,此时到了上图,这时 singletonObjet 肯定没有,因为AB都没有完全创建初始化好,singletonFactories 肯定有的,因为在创建的时候必须都是由这个bean对象的工厂类来通过构造方法实例化对象,并在这个过程在 singletonsCurrentlyInCreation 上面存储对应的bean 名称,所以这时就返回了未初始化好的A给B,这样 AutowiredAnnotationBeanPostProcessor 就可以实现属性的注入功能;接着:
此处代码也非常关键:
点进去:
在这实现了beanNameAware,BeanClassLoaderAware,BeanFactroyAware感知接口的调用;接着:
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
这里实现了BBP的before调用;接着:invokeInitMethods
这里实现了 InitializingBean 接口的调用,
最后:wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 实现BBP的 after 调用;回到主干,到了:
在这里开始了:
在这里 singletonObjects 肯定不存在A的,earlySingletonObjects 也不存在的,allowEarlyReference 为 false, 所以返回 null;
一路回到工厂类:
可以看出来B对象已经初始化好了(但是A没有初始化);跟B一样,最后回到A的属性注入方法那里,
完成BBP以及初始化接口的调用,再将对应的缓存更新即可;
好了,上面已经分析了Bean在实例化以及初始化的处理:
总结下来:spring Bean的生命周期是紧紧结合扩招接口的,dubbo,aop以及事务的扩展等等都在此功能上实现的;同时为了解决属性依赖的问题,spring 利用了 bbp的扩展接口:AutowiredAnnotationBeanPostProcessor ,来区分对象或者是普通的对象来实现属性的注入功能,同时,为了满足解决循环依赖的问题,引入了递归+缓存的标志方法来实现;
图表示 :