深入源码理解SpringBean生命周期
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
作者 | DeepSleeping丶
来源 | urlify.cn/jy6NJr
概述
本文描述下Spring的实例化、初始化、销毁,整个SpringBean生命周期,聊一聊BeanPostProcessor的回调时机、Aware方法的回调时机、初始化方法的回调及其顺序、销毁方法的回调及其顺序、重要的BeanPostProcessor的介绍。
开头是一张我画的调用流转图,然后就是我写的一个Demo通过日志打印了SpringBean的生命周期,最后通过源码慢慢跟进其生命周期。
生命周期流转图
生命周期Demo
如下对某一个Bean进行getBean操作,最后销毁上下文,通过日志来查看SpringBean的生命周期
代码
package com.deepz.spring;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Slf4j
@Configuration
public class BeanLifeCycleManager {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanLifeCycleManager.class);
context.getBean("beanLifeCycle");
context.close();
}
@Bean(initMethod = "init", destroyMethod = "destroyMethod")
public BeanLifeCycle beanLifeCycle() {
return new BeanLifeCycle();
}
interface MyAware extends ApplicationContextAware, EnvironmentAware, BeanFactoryAware {
}
@Component
static class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if ("beanLifeCycle".equals(beanName)) {
log.info(">>>>>>>>>>元信息收集 ,MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) \nbeanDefinition = [{}]\n,beanType = [{}],beanName = [{}]\n", beanDefinition, beanType, beanName);
}
}
}
@Component
static class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if ("beanLifeCycle".equals(beanName)) {
log.info(">>>>>>>>>>实例化前,InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(Class<?> beanClass,String beanName) \nbeanClass = [{}],beanName = [{}]\n", beanClass, beanName);
}
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if ("beanLifeCycle".equals(beanName)) {
log.info(">>>>>>>>>>实例化后,InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation(Object bean, String beanName)\nbean = [{}],beanName = [{}]\n", bean, beanName);
}
return false;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if ("beanLifeCycle".equals(beanName)) {
log.info(">>>>>>>>>>初始化前,InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization(Object bean, String beanName)\nbean= [{}],beanName = [{}]\n", bean, beanName);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if ("beanLifeCycle".equals(beanName)) {
log.info(">>>>>>>>>>初始化后,InstantiationAwareBeanPostProcessor#postProcessAfterInitialization(Object bean, String beanName)\nbean= [{}],beanName = [{}]\n", bean, beanName);
}
return bean;
}
}
public static class BeanLifeCycle implements InitializingBean, MyAware, DisposableBean {
public void init() {
log.info(">>>>>>>>>>init-method\n");
}
@PostConstruct
public void postConstruct() {
log.info(">>>>>>>>>>postConstruct\n");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info(">>>>>>>>>>afterPropertiesSet\n");
}
public void destroyMethod() {
log.info(">>>>>>>>>>destroy-method\n");
}
@Override
public void destroy() {
log.info(">>>>>>>>>>DisposableBean-destroy\n");
}
@PreDestroy
public void preDestroy(){
log.info(">>>>>>>>>>preDestroy\n");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
log.info(">>>>>>>>>>BeanFactoryAware#setBeanFactory\n");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
log.info(">>>>>>>>>>ApplicationContextAware#setApplicationContext\n");
}
@Override
public void setEnvironment(Environment environment) {
log.info(">>>>>>>>>>EnvironmentAware#setEnvironment\n");
}
}
}
执行结果
实例化前
从createBean开始,见证Bean的实例化过程,首先是Bean实例化前的一个扩展点,它允许你自定义返回Bean实例。(AOP生成代理对象的入口之一,但基本不会走这里)
回调Bean实例化前的方法
AbstractAutowireCapableBeanFactory#createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
主要是为了回调所有InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation(Class<?> beanClass, String beanName)方法,该方法会返回Object对象,如果返回的Object不为空,则会回调所有BeanPostProcessor的postProcessAfterInitialization(Object bean, String beanName)方法,那么返回的Object则会作为Bean去处理,如果返回Null,那么后续就会交由Spring来实例化、初始化(doCreateBean)。
自定义拦截实例化Bean后回调Bean后置方法
实例化
AbstractAutowireCapableBeanFactory#doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
如源码所示,如果上述扩展点没有return,那么就会进入到doCreateBean方法
首先是对Bean进行实例化,其中包括了构造器推断等,本文不过多聊这块内容,最后会返回BeanWrapper包裹的Bean实例。
元信息收集
实例化之后Spring通过回调MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)对一些元信息做了收集维护处理,如@Autowire、@Resource、@PostConstruct 和 @PreDestroy等,为后续属性注入做准备。
MergedBeanDefinitionPostProcessor的实现类
MergedBeanDefinitionPostProcessor回调
初始化
实例化完了,对一些需要收集的信息也准备好了,后续就是进行属性注入和回调初始化方法了,其中populateBean方法是属性填充,initializeBean是回调初始化方法。
InstatiationAwareBeanPostProcessor回调postProcessAfterInstantiation方法
AbstractAutowireCapableBeanFactory#populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw)
Aware接口回调
AbstractAutowireCapableBeanFactory#initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
部分Aware接口回调、BeanPostProcessor的初始化前置回调(包括PostConstruct的调用、其余Aware的回调)、afterPropertiesSet回调、自定义init方法回调、BeanPostProcessor的初始化后置回调
部分Aware回调
AbstractAutowireCapableBeanFactory#invokeAwareMethods(final String beanName, final Object bean
BeanPostProcessor的初始化前置回调
重要BeanPostProcessor如下:
ApplicationContextAwareProcessor#postProcessBeforeInitialization(final Object bean, String beanName)回调剩余Aware方法
InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization(final Object bean, String beanName)回调PostConstruct方法
回调初始化方法
AbstractAutowireCapableBeanFactory#invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
先回调InitializingBean的afterPropertiesSet方法,随后回调自定义的init-method
BeanPostProcessor的初始化后置回调
注意:AOP生成代理的主要入口便是这里的了,对应的BeanPostProcessor->AbstractAutoProxyCreator。(后续单聊AOP相关源码,FLAG)
销毁
销毁方法最终会走到DisposableBeanAdapter的destroy方法去做处理,与初始化方法类似,这里简单介绍把。
看图就能发现,顺序执行的,先是注解方法,然后是DisposableBean的回调,最后是自定义的销毁方法,就是如此简单。
粉丝福利:Java从入门到入土学习路线图
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈