Spring Bean生命周期
前言
在使用Spring框架进行开发,一般我们都会将项目中的Bean托管给Spring,也就是俗称的IOC
被Spring管理的单例(singleton)Bean 从创建到销毁,中间的过程都会有完整的生命周期,原型(prototype)Bean只有创建的生命周期没有销毁的生命周期,因为Spring在创建完原型Bean之后就不再有Bean的控制权,而是交由用户控制
文中主要结合源码分析单例Bean 的生命周期
1. 流程
启动Spring
public class BeanLifecycleAnalyse {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.refresh();
applicationContext.close();
}
}
Spring启动要调用ApplicationContent的refresh()方法
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();
}
}
}
finishBeanFactoryInitialization内部主要进行Bean初始化相关内容
AbstractApplcationContent#finishBeanFactoryInitialization() 源码
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.
// 创建单例Bean
beanFactory.preInstantiateSingletons();
}
在 preIntaniateSingletons中会依次按照BeanDefinition的顺序依次初始化Bean
DefaultListableBeanFactory#preIntaniateSingletons() 源码
@Override
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 beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 根据BeanDefinition的顺序初始化单例对象
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)
((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) {
smartSingleton.afterSingletonsInstantiated();
}
}
}
2. AbstractAutowireCapableBeanFactory#createBean()
createBean方法内部就是实例化Bean逻辑的开始
源码中只保留实例化Bean的逻辑
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
// ...省略其他代码....
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
// 实例化Bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
3. 实例化前阶段
源码中 resolveBeforeInstantiation 方法属于实例化前阶段,该阶段会查找Spring中的类型为InstantiationAwareBeanPostProcessor 的BeanPostProcessor,并调用postProcessBeforeInstantiation() 方法进行实例化前置处理
源码
AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation()
protected Object applyBeanPostProcessorsBeforeInstantiation(Class> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
InstantiationAwareBeanPostProcessor 结构
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
@Nullable
default Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException {
return null;
}
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return null;
}
default PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
}
在createBean方法中可以看到,如果该接口的方法返回值不为空,则直接将该对象返回不进行下面的实例化和初始化逻辑,一般该方法用于返回代理对象
4. 实例化阶段
doCreateBean() 源码
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// ...省略其他代码.....
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建Bean实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Initialize the bean instance.
Object exposedObject = bean;
// 对Bean进行属性填充
populateBean(beanName, mbd, instanceWrapper);
// 初始化Bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
return exposedObject;
}
createBeanInstance会创建Bean实例并返回
createBeanInstance 源码
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class> beanClass = resolveBeanClass(mbd, beanName);
Supplier> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Candidate constructors for autowiring?
// 选取构造器
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
该方法主要确定该调用Bean中的哪个构造方法进行实例化
determineConstructorsFromBeanPostProcessors方法内部会获取类型为SmartInstantiationAwareBeanPostProcessor 的BeanPostProcessor,并执行其determineCandidateConstructors方法, 该方法会返回构造方法数组,实现该接口可以自由选取使用哪个构造方法
4. 属性填充
populateBean方法内部会将Bean的属性进行完善
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// ... 省略其他代码。。。。。
// 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.
// 实例化后置处理
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
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 (pvs != null) {
// 属性填充
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
-
属性填充前
属性填充前进行 实例化后置处理 InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
调用 InstantiationAwareBeanPostProcessor#postProcessProperties 对属性进行定制操作 -
属性填充
执行applyPropertyValues 内部实际调用的字段的setter方法进行变量赋值
5. 初始化
初始化逻辑在initializeBean() 方法中
源码
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 回调Aware接口
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// BeanPostProcessor 初始化前置处理
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行初始化方法
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初始化后置处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
通过源码可以看到初始化分为三个阶段 初始化前,初始化,初始化后
-
初始化前
初始化前执行 invokeAwareMethods方法来回调各个Aware接口的方法,并进行前置处理
invokeAwareMethods 源码
private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }
Spring中一共有九个Aware接口,这里的方法只会执行前三个,后续的六个在前置处理applyBeanPostProcessorsBeforeInitialization方法中
applyBeanPostProcessorsBeforeInitialization源码
@Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
通过对这段代码debug,可以看到Spring内置了六个BeanPostProcessor,其中剩下六个Aware接口的回调都由第一个ApplicationContextAwareProcessor处理
ApplicationContextAwareProcessor 源码
class ApplicationContextAwareProcessor implements BeanPostProcessor { private final ConfigurableApplicationContext applicationContext; private final StringValueResolver embeddedValueResolver; /** * Create a new ApplicationContextAwareProcessor for the given context. */ public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) { this.applicationContext = applicationContext; this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory()); } @Override @Nullable public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // ...省略其他代码... invokeAwareInterfaces(bean); return bean; } private void invokeAwareInterfaces(Object bean) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } }
通过源码可以看出来在前置处理方法postProcessBeforeInitialization中会依次调用六个Aware接口进行回调
BeanProcessor集合中还有一个CommonAnnotationBeanPostProcessor类,在这个类中的前置方法处理还会调用注解@PostConstruct标注的方法
-
初始化阶段
初始化会依次调用InitializingBean#afterPropertiesSet 方法和自定义的initMethod
invokeInitMethods 源码
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isTraceEnabled()) { logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } // 如果实现InitializingBean接口,此处会回调afterPropertiesSet方法 ((InitializingBean) bean).afterPropertiesSet(); } // 执行initMethod if (mbd != null && bean.getClass() != NullBean.class) { String initMethodName = mbd.getInitMethodName(); if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } } }
- 初始化后阶段
执行BeanPostProcessor的后置处理
applyBeanPostProcessorsAfterInitialization源码
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
// 初始化后置处理
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
这一阶段会依次执行各个BeanPostProcessor的后置处理方法postProcessAfterInitialization,通过实现该接口可以实现对Bean的自定义处理
6.所有Bean初始化后
在所有的Bean都经历过上述过程后,Bean已经初始化完成,所有的Bean都已经准备好使用
此时在DefaultListableBeanFactory#preInstantiateSingletons中会进行最后一步回调
public void preInstantiateSingletons() throws BeansException {
// ....省略实例化和初始化代码
// 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
源码中会循环已经初始化完成的Bean,如果该Bean实现了SmartInitializingSingleton接口则进行afterSingletonsInstantiated方法的回调
这一步和上述初始化流程不同,初始化时是挨个实例化Bean并初始化。这一步是等待所有Bean全部初始化完成,所有Bean都已经是可使用的状态
实现这一接口可以对Bean进行最后的定制操作或其他操作
7.销毁阶段
在Spring应用上下文关闭时,会对Spring中的对象依次进行销毁
销毁操作在 DisposableBeanAdapter#destroy 方法中
源码
public void destroy() {
// 销毁前置处理
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
if (this.invokeDisposableBean) {
try {
// 执行接口销毁方法
((DisposableBean) this.bean).destroy();
}
}
if (this.destroyMethod != null) {
// 执行自定义destroyMethod
invokeCustomDestroyMethod(this.destroyMethod);
}
else if (this.destroyMethodName != null) {
Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
if (methodToInvoke != null) {
invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
}
}
}
销毁流程和初始化流程类似 分为销毁前和销毁阶段
-
销毁前
调用DestructionAwareBeanPostProcessor#destroy 方法,进行前置处理,被@PreDestroy标注的方法也会在这一阶段由CommonAnnotationBeanPostProcessor#postProcessBeforeDestruction 方法执行(该方法由其父类InitDestroyAnnotationBeanPostProcessor实现)
-
销毁阶段
如果Bean实现了DestructionAwareBeanPostProcessor接口,则调用其destroy方法
如果指定了Bean的destroyMethod则执行其销毁方法
总结
Bean生命周期流程
-
Bean实例化阶段 AbstractAutowireCapableBeanFactory#createBeanInstance
实例化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 前置处理
实例化:AbstractAutowireCapableBeanFactory#createBeanInstance 创建Bean实例
-
Bean属性填充阶段 AbstractAutowireCapableBeanFactory#populateBean
属性填充前:InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation 后置处理
InstantiationAwareBeanPostProcessor#postProcessProperties 属性处理属性填充:AbstractAutowireCapableBeanFactory#applyPropertyValues 属性设置
-
Bean实例化阶段 AbstractAutowireCapableBeanFactory#initializeBean
实例化前:AbstractAutowireCapableBeanFactory#invokeAwareMethods Aware接口回调,
@PostConstruct方法调用实例化:AbstractAutowireCapableBeanFactory#invokeInitMethods 初始化方法回调
InitializingBean#afterPropertiesSet,initMethod实例化后:SmartInitializingSingleton#afterSingletonsInstantiated 实例化后回调
-
销毁阶段 DisposableBeanAdapter#destroy
销毁前:DestructionAwareBeanPostProcessor#postProcessBeforeDestruction 销毁前置处理,
@PreDestroy 方法回调销毁:执行销毁方法 DisposableBean#destroy,destroyMethod