Spring声明周期简单介绍
介绍
Spring生命周期
- 1.第一部分 Spring生命周期为BeanFactory的初始化,这部分内容主要是Spring MetaData的加载,即如何将定义的Bean从xml,Annotation,JavaBean这三种形式变成Spring能识别的BeanDefinitions.这里有一个很关键的回调接口,BeanFactoryPostProcessor,完成BeanFactory的初始前后会回调这个接口。
- 2.第二部分 Spring对BeanDefinitions解析的一个过程,完成IOC和AOP的过程,这里Bean初始化过程为如图所示:1.实例化(new 一个Bean) 2.属性赋值(完成依赖注入) 3.初始化(调用Bean的构造器等) 4.销毁(destory),与BeanFactoryPostProcessor对应,完成Bean声明周期回调的接口为BeanPostPorcessor。
Spring声明周期调用图
以一个例子介绍
```Java
package it.caoxin.ioctest4_beanlifecycle.bean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 功能描述:控制Spring Bean的声明周期
* The InitializingBean and DisposableBean callback interfaces
* Custom init() and destroy() methods
* The @PostConstruct and @PreDestroy annotations. You can combine these mechanisms to control a given bean.
* 修改日期:2020/3/9
* 修改描述:
*/
@Component
public class BeanLifeCycle implements InitializingBean, DisposableBean {
public BeanLifeCycle() {
System.out.println("--------------------1.Constractor");
}
@PostConstruct
public void postConstruct() {
System.out.println("---------------------2.postConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
// 对应的代码配置代码
//
System.out.println("--------------------3.afterPropertiesSet");
}
@PreDestroy
public void preDestory() {
System.out.println("---------------------4.preDestory");
}
@Override
public void destroy() throws Exception {
// 对应的配置代码
//
System.out.println("--------------------5.destory");
}
}
```
-- 程序的执行结果为:从Spring.io中声明周期部分可以找到以下部分代码
--------------------1.Constractor
---------------------2.postConstruct
--------------------3.afterPropertiesSet
---------------------4.preDestory
--------------------5.destory
如何证明BeanFactory初始化时会回调 生命周期回调接口呢?
-- 从上图中可以看到Interface BeanDefinitionResgisterPostProcessor是实现了Interface BeanPostProcessor,我们先增加两个类,一个类实现BeanDefinitionResgisterPostProcessor另外一个类是实现了BeanPostProcessor;代码如下
BeanPostProcessor接口实现类
```Java
@Component
public class BeanLifeBeanPostProcess implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"---------1.BeanLifeBeanPost before------");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"---------2.BeanLifeBeanPost after------");
return bean;
}
}
```
BeanDefinitionRegistryPostProcessor接口实现类
```Java
@Component
public class BeanLifeBeanDefinitionRegisterPostProcess implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("1.BeanFactory----------------");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("2.BeanFactory-----------------");
}
}
```
- 观察程序程序执行的结果我们可以发现
- 1.BeanFactory----------------
- 2.BeanFactory-----------------
- 3.BeanFactory-----------------
- -------------------1.Constractor
- --------------------2.postConstruct
- -------------------3.afterPropertiesSet
- --------------------4.preDestory
- -------------------5.destory
- 这里我们证明了Spring BeanFactory初始化的回调。
如何证明Bean初始化时会回调 生命周期回调接口呢?
- 我们再写两个类
- 第一个BeanPostProcessor
``` Java
@Component
public class BeanLifeBeanPostProcess implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"---------1.BeanLifeBeanPost before------");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"---------2.BeanLifeBeanPost after------");
return bean;
}
}
```
- 第二个InstantiationAwareBeanPostProcessor
``` Java
@Component
public class BeanLifeInitilaztionBeanPostProcess implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
System.out.println(beanName+"--------1.BeanInitilaztion before---------");
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"--------2.BeanInitilaztion after---------");
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
System.out.println(beanName+"--------3.BeanInitilaztion propertyvalue---------");
return null;
}
}
```
- 程序运行结果
- 1.BeanFactory----------------
- 2.BeanFactory-----------------
- 3.BeanFactory-----------------
- 读者可以先不看appConfig
- appConfig--------1.BeanInitilaztion before---------
- appConfig--------2.BeanInitilaztion after---------
- appConfig--------3.BeanInitilaztion propertyvalue---------
- appConfig---------1.BeanLifeBeanPost before------
- appConfig---------2.BeanLifeBeanPost after------
- 读者可以先不看appConfig
- beanLifeCycle--------1.BeanInitilaztion before---------
- -------------------1.Constractor
- beanLifeCycle--------2.BeanInitilaztion after---------
- beanLifeCycle--------3.BeanInitilaztion propertyvalue---------
- beanLifeCycle---------1.BeanLifeBeanPost before------
- ---------------------2.postConstruct
- --------------------3.afterPropertiesSet
- beanLifeCycle---------2.BeanLifeBeanPost after------
- ---------------------4.preDestory
- --------------------5.destory
- 最终的结果是:
- 1.BeanFactory----------------
- 2.BeanFactory-----------------
- 3.BeanFactory-----------------
- beanLifeCycle--------1.BeanInitilaztion before---------
- -------------------1.Constractor
- beanLifeCycle--------2.BeanInitilaztion after---------
- beanLifeCycle--------3.BeanInitilaztion propertyvalue---------
- beanLifeCycle---------1.BeanLifeBeanPost before------
- ---------------------2.postConstruct
- --------------------3.afterPropertiesSet
- beanLifeCycle---------2.BeanLifeBeanPost after------
- ---------------------4.preDestory
- --------------------5.destory
- 可以看出实现InstantiationAwareBeanPostProcessor的三个方法会先于BeanPostProcessor的三个方法执行并穿插在BeanLifeCycle中。这里分析一下BeanPostProcessor接口,大家可以使用Idea展示一下BeanPostProcessor,实现类众多其实大致可以分为三类:
- 第一类:
- 影响多个Bean接口;BeanPostProcessor接口用于用户自定义扩展,BeanPostProcessor执行阶段的源码穿插在Aware接口调用。
- 第二类:
- 只调用一次的接口
- 1.Aware接口 顾名思义可以拿到资源如BeanNameAware接口,稍后Dubbo服务导出中会分析到。分类他们会在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods中进行调用
- 一组
- BeanNameAware 获取BeanDefinition的名字
- BeanClassLoaderAware 获取类加载器
- BeanFactoryAware 获取BeanFactory
- 二组
- EnvironmentAware 获取Spring环境
- ApplicationContextAware
- ApplicationEventPulisherAware
- MessageSoureAware
- ResourceLoaderAware
最后介绍一个Spring源码中声明周期的大致调用链
- org.springframework.context.support.AbstractApplicationContext#refresh中
```Java
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// BeanFactoryProcessors调用点(重要)--1.ConfigurationClassPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 所有BeanPostProcessors注册的调用点
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有非懒加载的单例Bean的调用点(重要)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
```
- Bean的初始化流程在finishBeanFactoryInitialization中有兴趣的读者可以详细了解 一下,具体创建Bean的过程在
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean中
对应实例化阶段
```Java
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 1.Bean声明周期 实例化阶段
// 第2次调用PostProcessor
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
```
对应属性赋值阶段 ```Java // 2.Bean声明周期 属性赋值阶段 平常所说的依赖注入就时在这个过程 // 第5和第6次调用PostProcessor populateBean(beanName, mbd, instanceWrapper); ```
对应初始化阶段 ```Java // 3.Bean声明周期 初始化阶段 // 第7和第8次调用PostProcessor exposedObject = initializeBean(beanName, exposedObject, mbd); ```
对应销毁阶段 ```Java ApplicationConfigAnnotation context new ApplicationConfigAnnotation(); context.close(); ```