WHCSRL 技术网

还记不住Spring Bean的生命周期?看这篇你就知道方法了!

一、前言

上次我们在手把手教你解决循环依赖,一步一步地来窥探出三级缓存的奥秘中分析了Spring解决循环依赖的方式,在第6节中的doCreateBean(AbstractAutowireCapableBeanFactory类中)其实已经隐约看到了Bean的生命周期的几个阶段。

  1. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2. throws BeanCreationException {
  3. //实例化bean
  4. BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
  5. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  6. isSingletonCurrentlyInCreation(beanName));
  7. if (earlySingletonExposure) {
  8. //加入到三级缓存中,getEarlyBeanReference会返回单例工厂
  9. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  10. }
  11. Object exposedObject = bean;
  12. //属性赋值
  13. populateBean(beanName, mbd, instanceWrapper);
  14. //初始化
  15. exposedObject = initializeBean(beanName, exposedObject, mbd);
  16. if (earlySingletonExposure) {
  17. //从二级缓存中查找
  18. Object earlySingletonReference = getSingleton(beanName, false);
  19. if (earlySingletonReference != null) {
  20. //返回二级缓存中的bean,这里就有可能是代理后的对象
  21. exposedObject = earlySingletonReference;
  22. }
  23. }
  24. //销毁前的准备,注册待销毁的Bean
  25. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  26. return exposedObject;
  27. }

doCreateBean基本描述了Bean生命周期的大致框架——实例化、属性赋值与初始化,当然Bean最后一步就是销毁

基本阶段图

请记住这张图,也许你等会儿就不认识它了。


二、实例化与属性赋值阶段

当容器启动时,会依据配置或注解扫描指定的包,将其中的类转化为BeanDefinition,并集中在DefaultListableBeanFactory类的beanDefinitionMap变量里。

Spring中的BeanDdfinition,可以用来描述一个bean的作用域、是否懒加载、是否单例等。

容器启动完成后,当我们试图从容器获取一个Bean时,第一步就是去实例化该Bean。说白了,就是需要调用构造方法。

注意到在调用doCreateBean之前,调用了resolveBeforeInstantiation方法。

1、resolveBeforeInstantiation

  1. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. //省略部分代码
  4. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  5. if (bean != null) {
  6. return bean;
  7. }
  8. //正式进入生命周期
  9. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  10. return beanInstance;
  11. }
  12. protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
  13. Object bean = null;
  14. if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
  15. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  16. Class<?> targetType = determineTargetType(beanName, mbd);
  17. if (targetType != null) {
  18. //寻找InstantiationAwareBeanPostProcessor,并执行相应方法
  19. bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
  20. //在返回不为null的情况下,寻找BeanPostProcessor,执行相应方法
  21. if (bean != null) {
  22. bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
  23. }
  24. }
  25. }
  26. mbd.beforeInstantiationResolved = (bean != null);
  27. }
  28. return bean;
  29. }

当resolveBeforeInstantiation返回不为null的bean后,createBean会直接返回。也就是说,后续的实例化、属性赋值与初始化阶段都不会进行。这一步,将会给BeanPostProcessor一个返回代理而不是目前bean的机会。

resolveBeforeInstantiation核心的方法如下:

  1. protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
  2. //获取所有BeanPostProcessor的实现类
  3. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  4. //如果属于InstantiationAwareBeanPostProcessor类型,则执行postProcessBeforeInstantiation方法
  5. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  6. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  7. Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
  8. if (result != null) {
  9. return result;
  10. }
  11. }
  12. }
  13. return null;
  14. }
  15. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  16. throws BeansException {
  17. Object result = existingBean;
  18. //获取所有BeanPostProcessor的实现类
  19. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  20. //挨个执行postProcessAfterInitialization方法
  21. Object current = processor.postProcessAfterInitialization(result, beanName);
  22. if (current == null) {
  23. return result;
  24. }
  25. result = current;
  26. }
  27. return result;
  28. }

2、BeanPostProcessor

BeanPostProcessor是容器提供给我们的一个扩展接口,也称Bean的后置处理器。我们可以实现该接口,用来添加业务中特有的逻辑。

BeanPostProcessor实现类也是一个普通的Bean,那么Spring是怎么保证BeanPostProcessor实现类在开发人员写的Bean之前加载的呢?

这就要回到我们最熟悉的refresh方法中

  1. public void refresh() {
  2. // Prepare this context for refreshing.
  3. prepareRefresh();
  4. // Tell the subclass to refresh the internal bean factory.
  5. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  6. // Prepare the bean factory for use in this context.
  7. prepareBeanFactory(beanFactory);
  8. // Allows post-processing of the bean factory in context subclasses.
  9. postProcessBeanFactory(beanFactory);
  10. // Invoke factory processors registered as beans in the context.
  11. invokeBeanFactoryPostProcessors(beanFactory);
  12. // Register bean processors that intercept bean creation.
  13. registerBeanPostProcessors(beanFactory);
  14. // Initialize message source for this context.
  15. initMessageSource();
  16. // Initialize event multicaster for this context.
  17. initApplicationEventMulticaster();
  18. // Initialize other special beans in specific context subclasses.
  19. onRefresh();
  20. // Check for listener beans and register them.
  21. registerListeners();
  22. // Instantiate all remaining (non-lazy-init) singletons.
  23. finishBeanFactoryInitialization(beanFactory);
  24. // Last step: publish corresponding event.
  25. finishRefresh();
  26. }

其中registerBeanPostProcessors方法就会对BeanPostProcessor进行注册,在finishBeanFactoryInitialization中再完成非懒加载的单例Bean的加载。

从而BeanPostProcessor就会在业务Bean之前加载,因此可以在业务Bean实例化前进行调用。

3、instantiateBean

现在可以进入doCreateBean中,createBeanInstance包含了实例化bean并封装为BeanWrapper的逻辑,且内部提供了多种实例化的方式。

  1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  2. //将bean转化为class对象
  3. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  4. //基于Supplier实例化
  5. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  6. if (instanceSupplier != null) {
  7. return obtainFromSupplier(instanceSupplier, beanName);
  8. }
  9. //基于工厂方法实例化
  10. if (mbd.getFactoryMethodName() != null) {
  11. return instantiateUsingFactoryMethod(beanName, mbd, args);
  12. }
  13. //省略部分代码
  14. //基于有参构造函数实例化
  15. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  16. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
  17. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  18. return autowireConstructor(beanName, mbd, ctors, args);
  19. }
  20. //基于无参构造函数实例化
  21. return instantiateBean(beanName, mbd);
  22. }

有兴趣的同学,可以深入到这几种方式的内部,这里就不做探讨了。

4、populateBean

在实例化结束后,将进入属性赋值阶段。

  1. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  2. boolean continueWithPropertyPopulation = true;
  3. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  4. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  5. //如果属于InstantiationAwareBeanPostProcessor类型,则调用postProcessAfterInstantiation
  6. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  7. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  8. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  9. continueWithPropertyPopulation = false;
  10. break;
  11. }
  12. }
  13. }
  14. }
  15. //一旦任意一个InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation返回false,属性注入阶段将不再进行,直接进入下一个阶段
  16. if (!continueWithPropertyPopulation) {
  17. return;
  18. }
  19. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
  20. if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
  21. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  22. //按照名称注入
  23. if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
  24. autowireByName(beanName, mbd, bw, newPvs);
  25. }
  26. //按照类型注入
  27. if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
  28. autowireByType(beanName, mbd, bw, newPvs);
  29. }
  30. pvs = newPvs;
  31. }
  32. //省略掉InstantiationAwareBeanPostProcessor其他两个扩展点及下面的依赖检查
  33. if (pvs != null) {
  34. //属性注入
  35. applyPropertyValues(beanName, mbd, bw, pvs);
  36. }
  37. }

到这里,实例化与属性赋值阶段结束,我们整理一下其中的扩展点


 三、初始化阶段

从doCreateBean内的initializeBean开始

  1. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  2. //1.设置Aware相关依赖
  3. if (System.getSecurityManager() != null) {
  4. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  5. invokeAwareMethods(beanName, bean);
  6. return null;
  7. }, getAccessControlContext());
  8. }
  9. else {
  10. invokeAwareMethods(beanName, bean);
  11. }
  12. //2.调用BeanPostProcessor的前置处理
  13. Object wrappedBean = bean;
  14. if (mbd == null || !mbd.isSynthetic()) {
  15. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  16. }
  17. //3.1调用InitializingBean的afterPropertiesSet方法
  18. //3.2调用自定义的init method方法
  19. try {
  20. invokeInitMethods(beanName, wrappedBean, mbd);
  21. }
  22. catch (Throwable ex) {
  23. throw new BeanCreationException(
  24. (mbd != null ? mbd.getResourceDescription() : null),
  25. beanName, "Invocation of init method failed", ex);
  26. }
  27. //4.调用BeanPostProcessor的后置处理
  28. if (mbd == null || !mbd.isSynthetic()) {
  29. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  30. }
  31. return wrappedBean;
  32. }

1、设置Aware相关依赖

  1. private void invokeAwareMethods(final String beanName, final Object bean) {
  2. if (bean instanceof Aware) {
  3. //如果bean实现了BeanNameAware接口,则设置BeanName
  4. if (bean instanceof BeanNameAware) {
  5. ((BeanNameAware) bean).setBeanName(beanName);
  6. }
  7. //如果bean实现了BeanClassLoaderAware接口,则设置BeanClassLoader
  8. if (bean instanceof BeanClassLoaderAware) {
  9. ClassLoader bcl = getBeanClassLoader();
  10. if (bcl != null) {
  11. ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
  12. }
  13. }
  14. //如果bean实现了BeanFactoryAware接口,则设置BeanFactory
  15. if (bean instanceof BeanFactoryAware) {
  16. ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
  17. }
  18. }
  19. }

从这里可以看出,只要Bean实现了指定的Aware接口,Spring就会向Bean注入这些Aware相关信息。

2、调用BeanPostProcessor的前置处理

  1. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  2. throws BeansException {
  3. Object result = existingBean;
  4. //获取所有BeanPostProcessor的实现类
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. //挨个调用postProcessBeforeInitialization方法
  7. Object current = processor.postProcessBeforeInitialization(result, beanName);
  8. if (current == null) {
  9. return result;
  10. }
  11. result = current;
  12. }
  13. return result;
  14. }

这一步会获取容器中所有BeanPostProcessor的实现类,挨个调用postProcessBeforeInitialization方法。在其返回不为null的情况下,后一个结果会覆盖上一个结果。

当然在处理到ApplicationContextAwareProcessor的时候,会设置以下Aware依赖。

  • EnvironmentAware
  • EmbeddedValueResolverAware
  • ResourceLoaderAware
  • ApplicationEventPublisherAware
  • MessageSourceAware
  • ApplicationContextAware

在处理到InitDestroyAnnotationBeanPostProcessor,会找出被@PostConstruct注解修饰的方法,并执行。

3、invokeInitMethods

  1. protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
  2. throws Throwable {
  3. //如果实现了InitializingBean接口,则调用afterPropertiesSet方法
  4. boolean isInitializingBean = (bean instanceof InitializingBean);
  5. if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
  6. if (logger.isTraceEnabled()) {
  7. logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
  8. }
  9. if (System.getSecurityManager() != null) {
  10. try {
  11. AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
  12. ((InitializingBean) bean).afterPropertiesSet();
  13. return null;
  14. }, getAccessControlContext());
  15. }
  16. catch (PrivilegedActionException pae) {
  17. throw pae.getException();
  18. }
  19. }
  20. else {
  21. ((InitializingBean) bean).afterPropertiesSet();
  22. }
  23. }
  24. //调用xml中声明的init-method指定的方法
  25. if (mbd != null && bean.getClass() != NullBean.class) {
  26. String initMethodName = mbd.getInitMethodName();
  27. if (StringUtils.hasLength(initMethodName) &&
  28. !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
  29. !mbd.isExternallyManagedInitMethod(initMethodName)) {
  30. invokeCustomInitMethod(beanName, bean, mbd);
  31. }
  32. }
  33. }

4、调用BeanPostProcessor的后置处理

和前置处理类似,只是调用postProcessAfterInitialization方法,不再赘述。

因此,初始化过程又可以被细分为


四、销毁阶段

在容器关闭的时候,会进入Bean的销毁阶段,代码从AbstractApplicationContext的close()方法开始

不急着进入close()方法,先看一下第一节代码中最末尾的方法:

  1. protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
  2. AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
  3. //如果Bean不是多例且需要在容器关闭时销毁
  4. if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
  5. if (mbd.isSingleton()) {
  6. //给当前Bean绑定一个DisposableBeanAdapter
  7. registerDisposableBean(beanName,
  8. new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
  9. }
  10. else {
  11. // A bean with a custom scope...
  12. Scope scope = this.scopes.get(mbd.getScope());
  13. if (scope == null) {
  14. throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
  15. }
  16. scope.registerDestructionCallback(beanName,
  17. new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
  18. }
  19. }
  20. }
  21. public void registerDisposableBean(String beanName, DisposableBean bean) {
  22. synchronized (this.disposableBeans) {
  23. this.disposableBeans.put(beanName, bean);
  24. }
  25. }

在registerDisposableBeanIfNecessary中,会对每一个需要在容器关闭时进行销毁的单例Bean,绑定对应的DisposableBeanAdapter对象。最后把这些Bean及其DisposableBeanAdapter放入进名称为disposableBeans的map中,以供后续使用。

现在我们进入AbstractApplicationContext的close()方法

一路上兜兜转转,会进入到DefaultSingletonBeanRegistry的destroySingletons方法中

  1. public void destroySingletons() {
  2. String[] disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
  3. for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
  4. destroySingleton(disposableBeanNames[i]);
  5. }
  6. //省略部分代码
  7. }

先拿到所有待销毁Bean的名称,挨个调用destroySingleton方法,一直往下走,最终会进入到DefaultSingletonBeanRegistry的destroyBean中

其中核心的一句

  1. // Actually destroy the bean now...
  2. bean.destroy();

按照beanName从disposableBeans中获取到bean对应的DisposableBeanAdapter,调用其destroy方法

  1. public void destroy() {
  2. //调用被@PreDestroy注解修饰的方法
  3. //具体可以跟进InitDestroyAnnotationBeanPostProcessor类
  4. if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
  5. for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
  6. processor.postProcessBeforeDestruction(this.bean, this.beanName);
  7. }
  8. }
  9. //如果实现了DisposableBean接口,则调用destroy方法
  10. if (this.invokeDisposableBean) {
  11. if (System.getSecurityManager() != null) {
  12. AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
  13. ((DisposableBean) this.bean).destroy();
  14. return null;
  15. }, this.acc);
  16. } else {
  17. ((DisposableBean) this.bean).destroy();
  18. }
  19. }
  20. //调用xml中自定义的destroy-method方法
  21. if (this.destroyMethod != null) {
  22. invokeCustomDestroyMethod(this.destroyMethod);
  23. } else if (this.destroyMethodName != null) {
  24. Method methodToCall = determineDestroyMethod(this.destroyMethodName);
  25. if (methodToCall != null) {
  26. invokeCustomDestroyMethod(methodToCall);
  27. }
  28. }
  29. }

到这里,Bean的销毁过程基本就结束了,我们使用一张图来概括下:

 


 五、生命周期的全流程

我们整个阶段串联起来


六、代码验证

待观察的Bean

  1. public class A implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {
  2. private int id;
  3. public int getId() {
  4. return id;
  5. }
  6. public void setId(int id) {
  7. this.id = id;
  8. System.out.println("属性赋值");
  9. }
  10. private A() {
  11. System.out.println("实例化");
  12. }
  13. @PostConstruct
  14. public void postConstruct() {
  15. System.out.println("@PostConstruct指定的方法");
  16. }
  17. @Override
  18. public void setBeanClassLoader(ClassLoader classLoader) {
  19. System.out.println("BeanClassLoaderAware.setBeanClassLoader");
  20. }
  21. @Override
  22. public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  23. System.out.println("BeanFactoryAware.setBeanFactory");
  24. }
  25. @Override
  26. public void setBeanName(String name) {
  27. System.out.println("BeanNameAware.setBeanName");
  28. }
  29. @Override
  30. public void afterPropertiesSet() {
  31. System.out.println("InitializingBean.afterPropertiesSet");
  32. }
  33. public void initMethod() {
  34. System.out.println("xml中init-method指定的方法");
  35. }
  36. @PreDestroy
  37. public void preDestroy() {
  38. System.out.println("@PreDestroy指定的方法");
  39. }
  40. @Override
  41. public void destroy() {
  42. System.out.println("DisposableBean.destroy");
  43. }
  44. public void destroyMethod() {
  45. System.out.println("xml中destroy-method指定的方法");
  46. }
  47. }

自定义的BeanPostProcessor

  1. public class BeanPostProcessorImpl implements BeanPostProcessor {
  2. @Override
  3. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  4. if (beanName.equals("a")) {
  5. System.out.println("BeanPostProcessor.postProcessBeforeInitialization");
  6. }
  7. return bean;
  8. }
  9. @Override
  10. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  11. if (beanName.equals("a")) {
  12. System.out.println("BeanPostProcessor.postProcessAfterInitialization");
  13. }
  14. return bean;
  15. }
  16. }

自定义的InstantiationAwareBeanPostProcessorImpl

  1. public class InstantiationAwareBeanPostProcessorImpl implements InstantiationAwareBeanPostProcessor {
  2. @Override
  3. public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
  4. if (beanName.equals("a")) {
  5. System.out.println("InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");
  6. }
  7. return null;
  8. }
  9. @Override
  10. public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
  11. if (beanName.equals("a")) {
  12. System.out.println("InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");
  13. }
  14. //如果这里返回false,那么所有Bean将不进行属性赋值
  15. return true;
  16. }
  17. }

spring.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  7. <context:component-scan base-package="com.yang.ym"/>
  8. <bean id="a" class="com.yang.ym.testBean.A" init-method="initMethod" destroy-method="destroyMethod">
  9. <property name="id" value="1"/>
  10. </bean>
  11. <bean class="com.yang.ym.testBean.BeanPostProcessorImpl"/>
  12. <bean class="com.yang.ym.testBean.InstantiationAwareBeanPostProcessorImpl"/>
  13. </beans>

测试类

  1. @Test
  2. public void get() {
  3. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  4. A a = (A) context.getBean("a");
  5. System.out.println("关闭容器");
  6. context.close();
  7. }

输出结果:

  1. InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
  2. 实例化
  3. InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
  4. 属性赋值
  5. BeanNameAware.setBeanName
  6. BeanClassLoaderAware.setBeanClassLoader
  7. BeanFactoryAware.setBeanFactory
  8. BeanPostProcessor.postProcessBeforeInitialization
  9. @PostConstruct指定的方法
  10. InitializingBean.afterPropertiesSet
  11. xml中init-method指定的方法
  12. BeanPostProcessor.postProcessAfterInitialization
  13. 关闭容器
  14. @PreDestroy指定的方法
  15. DisposableBean.destroy
  16. xml中destroy-method指定的方法

七、总结

先记住4个大阶段,实例化、属性赋值、初始化与销毁。

在生命周期内部,可以自定义Bean后置处理器以及实现接口的形式来进行扩展

  • 容器级的扩展点,InstantiationAwareBeanPostProcessor与BeanPostProcessor。
  • Bean级的扩展点,Aware相关接口,InitializingBean与DisposableBean。

此外,可以使用注解或xml配置形式,指定扩展点

  • @PostConstruct注解
  • @PreDestroy注解
  • xml中init-method
  • xml中destroy-method

那么再记忆生命周期的先后顺序,就会容易很多:

getBean

  1. InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
  2. 实例化
  3. InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
  4. 属性赋值
  5. Aware接口回调
  6. BeanPostProcessor.postProcessBeforeInitialization
  7. @PostConstruct指定的方法
  8. InitializingBean.afterPropertiesSet
  9. xml中init-method指定的方法
  10. BeanPostProcessor.postProcessAfterInitialization

关闭容器后

  1. @PreDestroy指定的方法
  2. DisposableBean.destroy
  3. xml中destroy-method指定的方法

推荐阅读