Spring自問自答系列2----Bean生命週期

Spring中bean的聲明週期是怎麼樣的?spring

Bean初始化

BeanNameAware接口中setBeanName方法說明中說到:app

Set the name of the bean in the bean factory that created this bean. Invocked after population of normal bean peoperties but before an init callback such as InitializingBean#afterPropertiesSet()ide

說明注入屬性、invokeAwareMethods、init方法的執行具備前後次序。函數

注入屬性步驟:post

doCreateBean:553, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support):
// 該方法注入參數
populateBean(beanName, mbd, instanceWrapper);

屬性注入內部實現的話是經過AutowiredAnnotationBeanPostProcessor對象注入參數this

經過AbstractAutowireCapableBeanFactory中initializeBean方法部分代碼能夠判斷出BeanPostProcessor中postProcessBeforeInitialization方法是在setBeanName方法以後、init方法前執行:code

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareMethods(beanName, bean);
				return null;
			}
		}, getAccessControlContext());
	} else {
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
	    // 執行postBeanProcessor的postProcessorBeforeInitialization方法
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}
	try {
	    // 執行bean的init方法
		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()) {
	// 執行postBeanProcessor的postProcessorAfterInitialization方法
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}
	return wrappedBean;
}

invokeInitMethods方法中先執行(若是有)afterPropertiesSet(),而後再執行bean的init方法。orm

初始化總結

  1. Instantiate(初始化Bean,調用構造函數,建立實例)
  2. Populate Properties(進行bean屬性設置,依賴注入)
  3. 若是bean實現Aware接口,執行Aware相關方法
  4. 執行postBeanProcessor的postProcessorBeforeInitialization方法
  5. 若是有,則執行afterPropertiesSet方法
  6. 執行init-method
  7. 執行postBeanProcessor的postProcessorAfterInitialization方法
  8. bean初始化完成

銷燬

銷燬比較簡單, 若是Bean實現DisposableBean執行destroy 調用自定義的destroy-method。對象

相關文章
相關標籤/搜索