概述
Bean 的生命周期(加载、使用、销毁)包括:
- 获取 Bean 定义(AbstractBeanFactory.getMergedLocalBeanDefinition)
- 实例化 Bean(AbstractAutowireCapableBeanFactory.createBeanInstance)
- Bean 属性填充(AbstractAutowireCapableBeanFactory.populateBean)
Bean 初始化(AbstractAutowireCapableBeanFactory.initializeBean)
- Aware 相关接口实现(BeanNameAware,BeanClassLoaderAware,BeanFactoryAware)
- 若实现了 BeanPostProcessor 接口,执行 ProcessBeforeInitialization 实现
- 执行标注了 @PostConstruct 注解的方法
- 若实现了 InitializingBean 接口,执行 afterPropertiesSet 方法
- 执行自定义的 init-method 方法(invokeInitMethods)
- 若实现了 BeanPostProcessor 接口,执行 postProcessAfterInitialization 实现
- 容器正常启动运行
- 程序运行结束,调用 DisposableBean 以及自定义的 destroyMethod
可以发现 Spring 在 Bean 初始化期间,留了较多的拓展点,我们能够实现拓展点从而对 Bean 进行增强,这也是 Spring 作为 IOC 容器带来的一个优势!
下图主要是 Bean 生命周期的流程展示:
样例程序
包含 3 个类:启动类 BeanInitApplication、样例类 A、以及对 A 进行前后增强的类 BeanPostProcessorConfig。
@SpringBootApplication
public class BeanInitApplication {
public static void main(String[] args) {
SpringApplication.run(BeanInitApplication.class, args);
}
// 定义 bean 的名称,自定义初始化方法,销魂方法
@Bean(name = "a", initMethod = "CustomInitMethod",destroyMethod = "CustomDestoryMethod")
public A getA(){
A a = new A();
return a;
}
}
public class A implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
System.out.println("A BeanClassLoaderAware setBeanClassLoader");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("A BeanFactoryAware setBeanFactory");
}
@Override
public void setBeanName(String s) {
System.out.println("A BeanNameAware setBeanName");
}
@Override
public void destroy() throws Exception {
System.out.println("A DisposableBean destroy");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("A InitializingBean afterPropertiesSet");
}
@PostConstruct
public void postContruct(){
System.out.println("A PostConstruct");
}
public void CustomInitMethod(){
System.out.println("A CustomInitMethod");
}
public void CustomDestoryMethod(){
System.out.println("A CustomDestoryMethod");
}
@PreDestroy
public void PreDestroyMethod(){
System.out.println("A PreDestroy");
}
}
@Component
public class BeanPostProcessorConfig implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass() == A.class){
System.out.println("A BeanPostProcessor postProcessBeforeInitialization " + beanName);
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass() == A.class){
System.out.println("A BeanPostProcessor postProcessAfterInitialization " + beanName);
}
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
执行结果,与上面图中的一样:
A BeanNameAware setBeanName
A BeanClassLoaderAware setBeanClassLoader
A BeanFactoryAware setBeanFactory
A BeanPostProcessor postProcessBeforeInitialization a
A PostConstruct
A InitializingBean afterPropertiesSet
A CustomInitMethod
A BeanPostProcessor postProcessAfterInitialization a
2021-07-15 17:28:22.981 INFO 111300 --- [ main] c.example.beaninit.BeanInitApplication : Started BeanInitApplication in 0.984 seconds (JVM running for 1.998)
A PreDestroy
A DisposableBean destroy
A CustomDestoryMethod
源码分析(省略部分代码)
再次说明,Bean 生命周期主要流程:
- 获取 Bean 定义
- 实例化
- 属性填充
- 初始化
- 结束
其中实例化、属性填充、初始化操作都在 AbstractAutowireCapableBeanFactory 类里面定义,下面具体分析。
1. AbstractBeanFactory
从 AbstractBeanFactory getBean 获取 Bean 开始分析:
public abstract class AbstractBeanFactory {
public Object getBean(String name) throws BeansException {
return this.doGetBean(name, (Class)null, (Object[])null, false);
}
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
// 从缓存中获取 Bean,调用 DefaultSingletonBeanRegistry.getSingleton(String name) 方法
Object sharedInstance = this.getSingleton(beanName); // 从缓存中获取 Bean
// 获取 Bean 定义
RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
// 作用域是单例情况
if (mbd.isSingleton()) {
// 调用 DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory<?> singletonFactory) 方法返回 Bean,这里有个匿名函数,讲在使用的时候再去调用具体的逻辑
sharedInstance = this.getSingleton(beanName, () -> {
try {
return this.createBean(beanName, mbd, args);
} catch (BeansException var5) {
this.destroySingleton(beanName);
throw var5;
}
});
// 返回 Bean 实例
beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
}
流程:
- 从缓存中获取 Bean;第一次请求返回 null
- 获取 Bean 的定义,主要是 getMergedLocalBeanDefinition 方法
- 调用 DefaultSingletonBeanRegistry 的 getSingleton 重载方法去获取 Bean 并返回(特别注意匿名函数的使用,执行到具体逻辑的时候才会去调用对应的方法)
可以发现最终是调用 DefaultSingletonBeanRegistry.getSingleton 获取 Bean。
2. DefaultSingletonBeanRegistry.getSingleton
public class DefaultSingletonBeanRegistry{
// 1
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256); // 一级缓存,存放初始化完成的对象
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16); // 三级缓存,存放为初始化对象的 beanFactory
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16); // 二级缓存,用于从三级缓存中获取增强的对象
private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap(16)); // 标记对象是否在创建中,创建中的对象会添加到里面
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
synchronized(this.singletonObjects) {
// 2
Object singletonObject = this.singletonObjects.get(beanName); // 从一级缓存中再次获取
if (singletonObject == null) {
// 3
this.beforeSingletonCreation(beanName); // 标志为创建中,beanName 加入到 singletonsCurrentlyInCreation
try {
// 4
singletonObject = singletonFactory.getObject(); // 匿名函数起作用,讲调用 AbstractAutowireCapableBeanFactory.createBean 方法并返回 ObjectFactory
newSingleton = true;
} catch (IllegalStateException var16) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw var16;
}
} finally {
// 5
this.afterSingletonCreation(beanName); // 创建完成,从 singletonsCurrentlyInCreation 标记中移除
}
// 6
if (newSingleton) {
this.addSingleton(beanName, singletonObject); // 将 Bean 加入到一级缓存,删除二级、三级缓存
}
}
return singletonObject;
}
}
}
流程:
- 成员属性:定义三级缓存和 Bean 正在创建中标识(这里只用记一下即可,后面系列文章会分析它们的作用)
- 加锁,再次从一级缓存中获取,显然第一次没有获取到
- 标记正在创建中, beforeSingletonCreation
- 执行 AbstractAutowireCapableBeanFactory.createBean 方法,返回初始化完成的 Bean
- 移除正在创建标记
- 将对象放到一级缓存,并删除二级、三级缓存,返回 Bean
可以发现最终是调用 AbstractAutowireCapableBeanFactory.createBean 获取 Bean
3. AbstractAutowireCapableBeanFactory.createBean
public abstract class AbstractAutowireCapableBeanFactory{
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
try {
// 1. 覆盖重写方法
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException var9) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var9);
}
Object beanInstance;
try {
// 2
beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
if (beanInstance != null) {
return beanInstance;
}
} catch (Throwable var10) {
}
try {
// 3 具体创建 Bean
beanInstance = this.doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
}
}
流程:
- 重写 Bean 中的方法
- 执行 InstantiationAwareBeanPostProcessor 拓展点的方法
- 执行 doCreateBean
doCreateBean 实现:
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (instanceWrapper == null) {
// 实例化 Bean
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}
// 是否单例 && 运行循环引用 && 创建中
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
// 实例化的 Bean 加入到 三级缓存
this.addSingletonFactory(beanName, () -> {
return this.getEarlyBeanReference(beanName, mbd, bean);
});
}
try {
// 属性填充
this.populateBean(beanName, mbd, instanceWrapper);
// 初始化
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
}
if (earlySingletonExposure) {
// 在从缓存中获取 Bean,涉及到将 Bean 从三级缓存移到二级缓存的过程,后面文章再分析
Object earlySingletonReference = this.getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
}
}
}
- 实例化 Bean,createBeanInstance
- 实例化的 Bean 放到 三级缓存
- 属性填充
- 初始化
初始化实现:
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
// 执行 aware 方法
this.invokeAwareMethods(beanName, bean);
return null;
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 执行 BeanPostProcessor 的前置实现
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}
try {
// 实现 afterPropertiesSet、自定义的 init 方法
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
if (mbd == null || !mbd.isSynthetic()) {
// 执行 BeanPostProcessor 的后置实现
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
总结
Bean 的生命周期,主要包含获取 Bean 定义、实例化、属性填充、初始化。
其中 AbstractAutowireCapableBeanFactory 定义了实例化、属性填充、初始化的具体实现,值得好好复习。
Bean 实例化首先加入到三级缓存,然后加入到二级缓存,初始化完成之后,将 Bean 放到了一级缓存中,之所以这样实现,是为了解决循环依赖的问题,后面文章进行详细分析。
初始化过程中,Spring 预留了较多拓展点,依次调用 Aware 接口、BeanPostProcessor、init-method 方法的具体实现,方便在生成 Bean 的过程中,做一些初始化赋值的操作。