Spring中bean的聲明週期是怎麼樣的?spring
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
銷燬比較簡單, 若是Bean實現DisposableBean執行destroy 調用自定義的destroy-method。對象