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

相关文章
相关标签/搜索