前言
Spring Bean生命週期是常見的面試題,也是日常開發中經常用到的技術點,在應用開發中,常常需要執行一些特殊的初始化工作,如建立資料庫連線,開啟網路連線,又比如在一些業務bean裡,你想拿到Spring IOC容器,又或者是想拿到一些已經例項化的Bean。同時,在服務結束時,也有一些銷燬銷燬工作需要執行。為了便於工作的設計,Spring IOC提供相關介面,可以讓應用定製Bean的初始化和銷燬。
Spring Bean生命週期
先來看一下Spring Bean生命週期流程圖,方便對照後續的原始碼分析。
Spring Bean生命週期從大的節點上分為4個過程:例項化、屬性賦值、初始化、銷燬。 日常業務開發過程中,我們應該涉及最多的兩個點就是初始化和銷燬,比如自定義Bean實現InitializingBean、DisposeableBean。
原始碼分析
Spring IOC容器初始化
初始化從AbstractAutowireCapableBeanFactory.doCreateBean方法開始說起,我在對應的程式碼位置標註了關鍵點
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}
//1. Bean例項化
if (instanceWrapper == null) {
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized(mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
} catch (Throwable var17) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
}
mbd.postProcessed = true;
}
}
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
this.addSingletonFactory(beanName, () -> {
return this.getEarlyBeanReference(beanName, mbd, bean);
});
}
Object exposedObject = bean;
try {
//2.屬性賦值
this.populateBean(beanName, mbd, instanceWrapper);
//3.初始化
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
} catch (Throwable var18) {
if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
throw (BeanCreationException)var18;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
}
if (earlySingletonExposure) {
Object earlySingletonReference = this.getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
String[] dependentBeans = this.getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
String[] var12 = dependentBeans;
int var13 = dependentBeans.length;
for(int var14 = 0; var14 < var13; ++var14) {
String dependentBean = var12[var14];
if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
try {
//4.銷燬 - 註冊回撥介面
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
} catch (BeanDefinitionValidationException var16) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
}
}
為了保持程式碼片段精簡,我刪掉了其中的logger程式碼。
從以上程式碼片段裡可以看到我們上面總結的Spring生命後期4個關鍵點都有體現,我們著重分析初始化和銷燬流程。
AbstractAutowireCapableBeanFactory.initializeBean
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
//1.檢查Aware相關介面並設定相關依賴
//BeanNameAware, BeanClassLoaderAware, BeanFactoryAware
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
this.invokeAwareMethods(beanName, bean);
return null;
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);
}
//2.BeanPostProcessor前置處理
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//BeanPostProcessor介面的postProcessBeforeInitialization回撥
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}
//3.若實現InitializingBean介面,則呼叫afterPropertiesSet()
//4.若配置自定義的init-method(), 則執行。
try {
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
//5.BeanPostProcessor後置處理
if (mbd == null || !mbd.isSynthetic()) {
//BeanPostProcessor介面的postProcessAfterInitialization回撥
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
AbstractAutowireCapableBeanFactory.invokeAwareMethods
invokeAwareMethod就是呼叫一系列Aware結尾的介面,比如
BeanNameAware、ApplicationContextAware、BeanFactoryAware。
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware)bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = this.getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware)bean).setBeanFactory(this);
}
}
}
AbstractAutowireCapableBeanFactory.invokeInitMethods
invokeinitMethods就是呼叫InitializingBean介面的afterPropertiesSet,並且檢查自定義init-method。
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
boolean isInitializingBean = bean instanceof InitializingBean;
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(() -> {
((InitializingBean)bean).afterPropertiesSet();
return null;
}, this.getAccessControlContext());
} catch (PrivilegedActionException var6) {
throw var6.getException();
}
} else {
((InitializingBean)bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
this.invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
從以上程式碼片段可以看出Spring IOC容器建立Bean的過程, 涉及的過程包括例項化,銷燬,還包括BeanPostProcessor介面相關方法實現,以上程式碼片段我們分析了Spring容器初始化過程載入Bean的各種實現,下面我們看下Spring容器銷燬階段。
容器銷燬
Spring容器銷燬過程呼叫鏈
Spring在這裡用了介面卡模式,也就是說最終的銷燬任務由DisposableBeanAdapter來完成,我們看下DisposeableBeanAdapter的結構。
從結構中可以看到bean屬性型別為Object, 也就是要銷燬的Bean,還有beanName屬性。
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
Iterator var1 = this.beanPostProcessors.iterator();
while(var1.hasNext()) {
DestructionAwareBeanPostProcessor processor = (DestructionAwareBeanPostProcessor)var1.next();
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
if (this.invokeDisposableBean) {
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
((DisposableBean)this.bean).destroy();
return null;
}, this.acc);
} else {
((DisposableBean)this.bean).destroy();
}
} catch (Throwable var3) {
}
}
if (this.destroyMethod != null) {
this.invokeCustomDestroyMethod(this.destroyMethod);
} else if (this.destroyMethodName != null) {
Method methodToInvoke = this.determineDestroyMethod(this.destroyMethodName);
if (methodToInvoke != null) {
this.invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
}
}
}
總結
Spring Bean生命週期分為4個階段和多個擴充套件點,擴充套件點又分為影響多個Bean和單個Bean。
4個階段:例項化、屬性賦值、初始化、銷燬。
擴充套件點
影響多個Bean
- BeanPostProcessor
- InstantiationAwareBeanPostProcessor
影響單個Bean
- BeanNameAware
- BeanFactoryAware
- BeanClassLoaderAware
- ApplicationContextAware
Spring生命週期中兩個關鍵的介面:InitializingBean, DisposableBean。