1. 介绍
Spring容器中Bean的生命周期由多个特定的生命阶段组成,每个生命阶段都开出了一扇门,允许外界借由此门对Bean施加控制。
2. 实现生命周期的方法
2.1 @Bean注解的initMethod和destroyMethod
这个属性设置的方法在spring叫做自定义init和destroy方法
@Configuration
@ComponentScan("com.qxgcloud.spring")
public class AppConfig {
@Bean(initMethod = "myInit", destroyMethod = "myDestroy")
public Dog getDog() {
return new Dog();
}
}
public class Dog implements InitializingBean, DisposableBean {
public void myInit() {
System.out.println("Dog myInit ...");
}
public void myDestroy() {
System.out.println("Dog myDestroy ...");
}
// ...
}
2.2 InitializingBean和DisposableBean接口
分别是两个接口:
- InitializingBean需要实现afterPropertiesSet方法
- DisposableBean需要实现destroy方法
public class Dog implements InitializingBean, DisposableBean {
// ...
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Dog afterPropertiesSet...");
}
@Override
public void destroy() throws Exception {
System.out.println("Dog destroy...");
}
2.3 @PostConstruct注解
在构造方法之后,但是初始化方法(2.1和2.2在spring中都叫做初始化方法)执行之前执行:
public class Dog implements InitializingBean, DisposableBean {
//...
@PostConstruct
public void postConstruct() {
System.out.println("Dog postConstruct...");
}
}
2.4 BeanPostProcessor
实现一个BeanPostProcessor,对所有bean都生效(内部通过逻辑控制也可对一部分bean生效):
@Component
public class MyBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("invoke postProcessBeforeInitialization " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("invoke postProcessAfterInitialization " + beanName);
return bean;
}
}
3. 生命周期的顺序
3.1 生命周期流程
3.1.1 检查Aware相关接口并设置相关依赖
AbstractAutowireCapableBeanFactory.java
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
检查三大类Aware组件(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware),并进行调用(里面的调用逻辑是用户自己写的)。
3.1.2 spring默认的6个后置处理器作用
- 前置方法:
- ApplicationContextAwareProcessor:判断bean是否是6大类Aware组件之一(EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware),若是则调用相应的Aware方法(里面的调用逻辑是用户自己写的)
- ConfigurationClassPostProcessor:
- PostProcessorRegistreationDelegate:啥也没干
- CommonAnnotationBeanPostProcessor(InitDestroyAnnotationBeanPostProcessor):调用生命周期方法,具体是检查是否有@PostContruct注解并调用
- AutowiredAnnotationBeanPostProcessor:啥也没干
- ApplicationListenerDetector:啥也没干
- 后置方法:
- ApplicationContextAwareProcessor:
- ConfigurationClassPostProcessor:
- PostProcessorRegistreationDelegate:啥也没干
- CommonAnnotationBeanPostProcessor(InitDestroyAnnotationBeanPostProcessor):
- AutowiredAnnotationBeanPostProcessor:啥也没干
- ApplicationListenerDetector:检查bean是否是ApplicationListener,若是则添加到容器事件管理中
3.1.3 spring生命周期必背代码
AbstractAutowireCapableBeanFactory.java
doCreateBean; {
populateBean(beanName, mbd, instanceWrapper); # 为bean属性赋值依赖注入,例如执行@Value注解和@Autowired注解
exposedObject = initializeBean(beanName, exposedObject, mbd); {
invokeAwareMethods(beanName, bean); # 检查并调用三大类Aware组件
# 遍历执行每个后置处理器的postProcessBeforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
# bean的初始化(afterPropertiesSet+initMethod)
invokeInitMethods(beanName, wrappedBean, mbd); {
((InitializingBean) bean).afterPropertiesSet(); # 执行InitializingBean接口的afterPropertiesSet方法
invokeCustomInitMethod(beanName, bean, mbd); # 执行@Bean指定的initMethod
}
# 遍历执行每个后置处理器的postProcessAfterInitialization方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
registerDisposableBeanIfNecessary(beanName, bean, mbd); # 注册bean的销毁生命周期
}
3.2 运行结果
对2中的所有生命周期函数进行运行,其输出如下:
invoke postProcessBeforeInitialization getDog
Dog postConstruct...
Dog afterPropertiesSet...
Dog myInit ...
invoke postProcessAfterInitialization getDog
Dog destroy...
Dog myDestroy ...