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。对象