Spring Bean生命周期及各个拓展点

Spring Bean生命周期

spring bean的加载过程很复杂,简单梳理下流程:

  1. 实例化(Instantiation)
  2. 属性赋值(Populate)
  3. 初始化(Initialization)
  4. 使用(Get bean)
  5. 销毁(destroy)

代码实现在AbstractAutowireCapableBeanFactory.doCreateBean()方法中:

  1. createBeanInstance() 实例化
  2. populateBean() 属性赋值
  3. initializeBean() 初始化

拓展接口

拓展接口分类

spring在bean加载过程中有多个拓展接口提供给用户进行功能拓展,但是并不方便记忆,简单来说分为三类拓展点:

对所有bean生效的拓展接口:

  1. BeanFactoryPostProcessor 可获取当前BeanFactory,进而获取bean definition等
  2. InstantiationAwareBeanPostProcessor 拓展【实例化】前后(before,after)(实际也是BeanPostProcessor的子类)
  3. BeanPostProcessor 拓展【初始化】前后,@PostConstruct注解也是在该处被调用

只对实现该接口的类生效的拓展接口

主要指Aware接口的各种实现:

  1. BeanNameAware,顾名思义,可以获取当前beanName(虽然该接口的方法名叫setBeanName())
  2. BeanClassLoaderAware 获取ClassLoader
  3. BeanFactoryAware,获取BeanFactory, 进而获取bean definition等

生命周期相关的接口

  1. InitializingBean 初始化接口
  2. DisposableBean 销毁接口

拓展接口调用顺序

流程图

Spring Bean生命周期及各个拓展点_第1张图片

代码验证

代码

  1. BeanFactoryPostProcessor的实现
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		GenericBeanDefinition beanDefinition = (GenericBeanDefinition) beanFactory.getBeanDefinition("person");
		System.out.println("【BeanFactoryPostProcessor】" + beanDefinition);
	}
}
  1. InstantitionAwareBeanPostProcessor实现
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		if (beanName.equals("person")) {
			System.out.println("【InstantiationAwareBeanPostProcessor-before】");
		}
		return null;
	}

	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		if (beanName.equals("person")) {
			System.out.println("【InstantiationAwareBeanPostProcessor-after】");
		}
		return false;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
		if (beanName.equals("person")) {
			System.out.println("【InstantiationAwareBeanPostProcessor-postProcessProperties】");
			pvs.forEach(pv -> System.out.println(pv.getName()));
		}
		return pvs;
	}
}
  1. BeanPostProcessor实现
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("person")) {
			System.out.println("【MyBeanPostProcessor-before-1】");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("person")) {
			System.out.println("【MyBeanPostProcessor-after-1】");
		}
		return bean;
	}

	@Override
	public int getOrder() {
		return 1;
	}
}
  1. 需要加载的类Person
@Component
public class Person implements BeanNameAware, BeanFactoryAware, BeanClassLoaderAware, InitializingBean, DisposableBean {

	@Autowired
	private Career career;
	private int id;

	public Person() {
		System.out.println("【实例化】调用Person的构造器实例化");
	}

	@Override
	public void setBeanName(String name) {
		System.out.println("==============Aware开始================");
		System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName() " + name);
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		System.out.println("【BeanClassLoaderAware接口】 " + classLoader);
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()" + beanFactory);
		System.out.println("==============Aware结束================");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		setId(1);
		System.out.println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
	}

	@PostConstruct
	public void postConstruct() {
		System.out.println("【PostConstruct】");
	}

	private void setId(int id) {
		this.id = id;
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("【DisposableBean接口】destroy-method");
	}
}

验证结果

17:14:07.582 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
17:14:07.596 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBeanFactoryPostProcessor'
17:14:07.597 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
【BeanFactoryPostProcessor】Generic bean: class [org.springframework.my.lifecycle.Person]; scope=singleton; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\myfile\start\spring-framework\integration-tests\build\classes\java\test\org\springframework\my\lifecycle\Person.class]
17:14:07.601 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
17:14:07.609 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
17:14:07.625 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
17:14:07.626 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBeanPostProcessor'
17:14:07.626 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'mySecondBeanPostProcessor'
17:14:07.626 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myInstantiationAwareBeanPostProcessor'
17:14:07.704 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myApp'
17:14:07.705 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'person'
【InstantiationAwareBeanPostProcessor-before】
【实例化】调用Person的构造器实例化
【InstantiationAwareBeanPostProcessor-after】
==============Aware开始================
【BeanNameAware接口】调用BeanNameAware.setBeanName() person
【BeanClassLoaderAware接口】 sun.misc.Launcher$AppClassLoader@18b4aac2
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()org.springframework.beans.factory.support.DefaultListableBeanFactory@5762806e: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,myApp,career,myBeanFactoryPostProcessor,myBeanPostProcessor,myInstantiationAwareBeanPostProcessor,mySecondBeanPostProcessor,person]; root of factory hierarchy
==============Aware结束================
【MyBeanPostProcessor-before-1】
【MyBeanPostProcessor-before-2】
【PostConstruct】
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【MyBeanPostProcessor-after-1】
【MyBeanPostProcessor-after-217:14:07.716 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'career'
【实例化Career】
【用户获取bean】org.springframework.my.lifecycle.Person@21de60b4
17:14:07.780 [SpringContextShutdownHook] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2d127a61, started on Thu May 28 17:14:06 CST 2020
【DisposableBean接口】destroy-method

参考来源

参考来源,尤其是第一个链接,讲解非常详细。
简书 《请别再问Spring Bean的生命周期了!》
CSDN 《Spring源码学习–Bean的生命周期》

你可能感兴趣的:(Spring Bean生命周期及各个拓展点)