乐趣区

关于javascript:JavaScript版数据结构与算法-轻松解决前端算法面试

download:JavaScript 版数据结构与算法 轻松解决前端算法面试

Spring5 源码 5 -Bean 生命周期后置处理器

次要阐明三种生命周期增强器:

BeanFactoryPostProcessor:BeanFactory 后置处理器

BeanDefinitionRegistryPostProcessor:bean 定义注册后置处理器
BeanFactoryPostProcessor
BeanPostProcessor:Bean 后置处理器

BeanPostProcessor
MergedBeanDefinitionPostProcessor
SmartInstantiationAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor
InitializingBean

DisposableBean (销毁的计划咱们临时不做阐明)

1.1 什么是 BeanPostProcessor
BeanPostProcessor 是 Spring 提供给咱们的一个十分重要的扩大接口,并且 Spring 外部的很多性能也是通过 BeanPostProcessor 来实现的(目前看到最典型的就是 AnnotationAwareAspectJAutoProxyCreator 的 注入)。

1.2 BeanPostProcessor 的品种
BeanPostProcessor 在 Spring 中的子类十分多(idea 显是有 46 个),比方

InstantiationAwareBeanPostProcessorAdapter:在 Spring 的 bean 加载过程中起了十分重要的作用
AnnotationAwareAspectJAutoProxyCreator:bean 创立过程中的 属性注入时起作用
AspectJAwareAdvisorAutoProxyCreator:Aspect 的 AOP 性能实现也全凭仗 BeanPostProcessor 的个性。
1.3 创立机会
BeanFactoryPostProcessor:在 Spring 启动时对 BeanDefinition 的创立 进行干涉解决。

BeanPostProcessor: 一是 Bean 对应的 BeanDefinition 的创立。二是 Bean 实例的创立。因为在 Spring 容器中,Bean 的创立并非仅仅通过反射创立就完结了,在创立过程中,须要思考到 Bean 针对 Spring 容器中的一些属性,所以 BeanDefinition 中不仅仅蕴含了 Bean Class 文件信息,还蕴含了 以后 Bean 在 Spring 容器中的一些属性,比方在容器中的作用域、是否懒加载、别名等信息。当 Bean 进行实例化创立时须要依赖于对应的 BeanDefinition 提供对应的信息。。

而因为 BeanPostProcessor 是参加了 Bean 创立过程。所以其创立肯定在一般 Bean 之前。实际上 BeanPostProcessor 的创立时在 Spring 启动时容器刷新的时候。

BeanPostProcessor 的 BeanDefinition 创立机会和一般 Bean 没有区别,都是在 Spring 启动时的 BeanFactoryPostProcessor 中实现(确切的说是 ConfigurationClassPostProcessor 中实现)。

而 BeanPostProcessor 的实例创立要优先于一般 bean 创立,Spring 启动过程中会调用 AbstractApplicationContext#registerBeanPostProcessors 办法。在这个办法中,Spring 会从容器中获取到所有 BeanPostProcessor 类型的 beanName,通过 beanFactory.getBean 办法获取到对应实例,进行排序后注册到 BeanFactory.beanPostProcessors 属性中. 当容器须要执行 BeanPostProcessor 办法时能够间接从 beanPostProcessors 中获取即可。

  1. 案例
    别离定义几个测试类,实现 bean 的后置处理器:

BeanDefinitionRegistryPostProcessor:

/**

  • BeanFactory 的后置处理器 , PriorityOrdered, Ordered
    */

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
public MyBeanDefinitionRegistryPostProcessor(){

  System.out.println("MyBeanDefinitionRegistryPostProcessor");

}

@Override // 紧接着执行
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

  System.out.println("MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...");

}

@Override // 先执行的
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

  System.out.println("MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...");
  // 加强 bean 定义信息的注册核心,比方本人注册组件

}
}
复制代码
BeanFactoryPostProcessor:

/**

  • BeanFactory 的后置处理器
    */

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

public MyBeanFactoryPostProcessor(){

  System.out.println("MyBeanFactoryPostProcessor...");

}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

  System.out.println("BeanFactoryPostProcessor....postProcessBeanFactory==>"+beanFactory);

}
}
复制代码
BeanPostProcessor:

/**

  • Bean 组件的 PostProcessor;
    */

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

public MyBeanPostProcessor(){

  System.out.println("MyBeanPostProcessor...");

}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

  System.out.println("MyBeanPostProcessor...postProcessAfterInitialization..."+bean+"==>"+beanName);
  return bean;

}

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

  System.out.println("MyBeanPostProcessor...postProcessBeforeInitialization..."+bean+"==>"+beanName);
  return bean; // new Object();

}
}
复制代码
InstantiationAwareBeanPostProcessor:

@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

public MyInstantiationAwareBeanPostProcessor(){

  System.out.println("MyInstantiationAwareBeanPostProcessor...");

}

// 初始化之前进行后置解决,Spring 留给咱们给这个组件创建对象的回调。
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {

  System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=>"+beanClass+"--"+beanName);
  //if(class.isAssFrom(Cat.class)){return new Dog()}
  // 如果咱们本人创立了对象返回。Spring 则不会帮咱们创建对象,用咱们本人创立的对象?咱们创立的这个对象,Spring 会保留单实例?还是每次 getBean 都调到咱们这里创立一个新的?return null;

}

// 是否让剩下的后置处理器对 bean 持续进行解决
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

  // 提前扭转一些 Spring 不论的 bean 外面的属性
  System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=>"+bean+"--"+beanName);
  return true; // 返回 false 则 bean 的赋值全副完结

}
// 解析自定义注解进行属性值注入;pvs 封装了所有的属性信息。
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)

     throws BeansException {//@GuiguValue();redis
  System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties=>"+bean+"--"+beanName);
  return null;

}

// public PropertyValues postProcessPropertyValues(
// PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
// System.out.println(“MyInstantiationAwareBeanPostProcessor…postProcessProperties”);
// return pvs;
// }
}
复制代码
MergedBeanDefinitionPostProcessor:

@Component
public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {

public MyMergedBeanDefinitionPostProcessor(){

  System.out.println("MyMergedBeanDefinitionPostProcessor...");

}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

  System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=>"+bean+"--"+beanName);
  return bean; //null

}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

  System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=>"+bean+"--"+beanName);
  return null;

}

@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {

  System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=>"+beanName+"--"+beanType+"---"+beanDefinition);

}

@Override
public void resetBeanDefinition(String beanName) {

  System.out.println("MyMergedBeanDefinitionPostProcessor...resetBeanDefinition.."+beanName);

}
}
复制代码
SmartInstantiationAwareBeanPostProcessor:

@Component //bean 进行代理加强期间进行应用
public class MySmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {

public MySmartInstantiationAwareBeanPostProcessor(){

  System.out.println("MySmartInstantiationAwareBeanPostProcessor...");

}

// 预测 bean 的类型,最初一次扭转组件类型。
public Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {

  System.out.println("MySmartInstantiationAwareBeanPostProcessor...predictBeanType=>"+beanClass+"--"+beanName);
  return null;

}

// 返回咱们要应用的结构器候选列表

public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {

  System.out.println("MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=>"+beanClass+"--"+beanName);
  // 返回一个咱们指定的结构器
  return null;

}

 // 返回晚期的 bean 援用,定义三级缓存中的 bean 信息

public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {

  System.out.println("MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=>"+bean+"--"+beanName);

  return bean; //

}

}
复制代码
InitializingBean:

@Component
public class CatInitializingBean implements InitializingBean {

public CatInitializingBean(){

  System.out.println("cat 被创立了...");

}

private String name;

@Value(“${JAVA_HOME}”) // 主动赋值性能
public void setName(String name) {

  System.out.println("cat....setName 正在赋值调用....");
  this.name = name;

}
// 注解怎么定义这个是初始化办法?
public String getName() {

  return name;

}

@Override
public void afterPropertiesSet() throws Exception {

  System.out.println("CatInitializingBean..afterPropertiesSet...");

}

@Autowired
private void init() {

  System.out.println("CatInitializingBean init....");

}

}
复制代码
debug 打点:在每个结构器和办法上都打上 断点,次要看看每个办法的执行机会是什么时候?

  1. 源码剖析
    入口还是:org.springframework.context.support.AbstractApplicationContext#refresh:

// 容器刷新的十二大步骤
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {

  // 容器启动的状态
  StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

  // Prepare this context for refreshing.
  // 1. 筹备上下文环境
  prepareRefresh();

  // Tell the subclass to refresh the internal bean factory.
  /** 1、创立 BeanFactory 对象
  *  2、xml 解析
  *  传统标签解析:bean、import 等
  *  自定义标签解析 如:<context:component-scan base-package="org.example"/>
  *  自定义标签解析流程:*     a、依据以后解析标签的头信息找到对应的 namespaceUri
  *     b、加载 spring 所以 jar 中的 spring.handlers 文件。并建设映射关系
  *     c、依据 namespaceUri 从映射关系中找到对应的实现了 NamespaceHandler 接口的类
  *     d、调用类的 init 办法,init 办法是注册了各种自定义标签的解析类
  *     e、依据 namespaceUri 找到对应的解析类,而后调用 paser 办法实现标签解析
  * 3、把解析进去的 xml 标签封装成 BeanDefinition 对象
  */
  // 2. 工厂创立:BeanFactory 第一次开始创立的时候,有 xml 解析逻辑
  ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

  // Prepare the bean factory for use in this context.
  // 3. 预筹备工厂,给容器中注册了环境信息作为单实例 Bean  不便后续主动拆卸
  // 并且放了一些后置处理器(监听、xxxAware 性能)prepareBeanFactory(beanFactory);

  try {
     //  Allows post-processing of the bean factory in context subclasses.
     // 留给子类的模板办法,容许子类持续对工厂执行一些解决
     postProcessBeanFactory(beanFactory);

     StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
     // Invoke factory processors registered as beans in the context.
     // 5.【大外围】工厂加强:执行所有的 BeanFactory 后置增强器 利用 BeanFactory 后置增强器对工厂进行批改或加强
     // 配置类也会在这个解析
     // BeanDefinitionRegistryPostProcessor BeanFactoryPostProcessor 实现对这两个接口的调用
     invokeBeanFactoryPostProcessors(beanFactory);

     // Register bean processors that intercept bean creation.
     // 6.【外围】注册 所有的 Bean 的后置处理器
     registerBeanPostProcessors(beanFactory);
     beanPostProcess.end();

     // Initialize message source for this context.
     // 7. 初始化国际化组件
     initMessageSource();

     // Initialize event multicaster for this context.
     // 8. 初始化事件派发 性能
     initApplicationEventMulticaster();

     // Initialize other special beans in specific context subclasses.
     // 9. 留给子类持续加强解决逻辑
     // 这个办法着重了解模板设计模式,因为在 springboot 中,这个办法是用来做内嵌 tomcat 启动的
     onRefresh();

     // Check for listener beans and register them.
     // 10. 注册事件监听器,从容器中获取所有的 ApplicationListener
     registerListeners();

     // Instantiate all remaining (non-lazy-init) singletons.
     // 11.【大外围】bean 创立:实现 BeanFactory 初始化(工厂外面所有的组件都好了)/*
      * 这个办法肯定要了解要具体看
      * 1、bean 实例化过程
      * 2、ioc
      * 3、注解反对
      * 4、BeanPostProcessor 的执行
      * 5、Aop 的入口
      */
     finishBeanFactoryInitialization(beanFactory);

     // Last step: publish corresponding event.
     // 12. 公布事件
     finishRefresh();}

  catch (BeansException ex) {if (logger.isWarnEnabled()) {
        logger.warn("Exception encountered during context initialization -" +
              "cancelling refresh attempt:" + ex);
     }

     // Destroy already created singletons to avoid dangling resources.
     destroyBeans();

     // Reset 'active' flag.
     cancelRefresh(ex);

     // Propagate exception to caller.
     throw ex;
  }

  finally {
     // Reset common introspection caches in Spring's core, since we
     // might not ever need metadata for singleton beans anymore...
     resetCommonCaches();
     contextRefresh.end();}

}
}
复制代码
咱们次要剖析几个办法:

3.1 invokeBeanFactoryPostProcessors(beanFactory)
BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor 办法解决都是在这个步骤中。

间接看 PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors():

public static void invokeBeanFactoryPostProcessors(

  ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-pro…

// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();

// 先拿到底层默认有的 BeanFactoryPostProcessor,容器会注入 ConfigurationClassPostProcessor,配置类的后置解决
if (beanFactory instanceof BeanDefinitionRegistry) {

  BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

  for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
        BeanDefinitionRegistryPostProcessor registryProcessor =
              (BeanDefinitionRegistryPostProcessor) postProcessor;
        registryProcessor.postProcessBeanDefinitionRegistry(registry);
        registryProcessors.add(registryProcessor);
     }
     else {regularPostProcessors.add(postProcessor);
     }
  }

  // Do not initialize FactoryBeans here: We need to leave all regular beans
  // uninitialized to let the bean factory post-processors apply to them!
  // Separate between BeanDefinitionRegistryPostProcessors that implement
  // PriorityOrdered, Ordered, and the rest.
  List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

  // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  // 首先,从工厂中获取所有的 BeanDefinitionRegistryPostProcessor
  String[] postProcessorNames =
        beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  // 获取所有实现 PriorityOrdered 接口的的 BeanDefinitionRegistryPostProcessor
  for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
        // 从工厂中获取这个组件(getBean 组件的创立)并放到这个汇合中
        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
        processedBeans.add(ppName);
     }
  }
  // 利用优先级排序
  sortPostProcessors(currentRegistryProcessors, beanFactory);
  registryProcessors.addAll(currentRegistryProcessors);
  // todo 执行这些 BeanDefinitionRegistryPostProcessor
  invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  currentRegistryProcessors.clear();

  // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  // 接下来,获取所有实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor
  for (String ppName : postProcessorNames) {
     // 即便实现了 Ordered 和 PriorityOrdered 接口,以 PriorityOrdered 接口为准
     if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
        processedBeans.add(ppName);
     }
  }
  // 排序
  sortPostProcessors(currentRegistryProcessors, beanFactory);
  registryProcessors.addAll(currentRegistryProcessors);
  invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  currentRegistryProcessors.clear();

  // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  // 最初,咱们自定义和没有实现 优先级接口的
  boolean reiterate = true;
  while (reiterate) {
     reiterate = false;
     postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
     for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
           processedBeans.add(ppName);
           reiterate = true;
        }
     }
     // 排序,依据类名大小写进行排序
     sortPostProcessors(currentRegistryProcessors, beanFactory);
     registryProcessors.addAll(currentRegistryProcessors);
     // todo 执行 BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry 办法
     invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
     // 避免反复
     currentRegistryProcessors.clear();}

  // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  // todo 接下来,执行 BeanDefinitionRegistryPostProcessor.postProcessBeanFactory 的办法
  invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);

}

else {

  // Invoke factory processors registered with the context instance.
  invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);

}

// todo 下面是执行 BeanDefinitionRegistryPostProcessor,上面是执行 BeanFactoryPostProcessor
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =

     beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {

  if (processedBeans.contains(ppName)) {// skip - already processed in first phase above}
  else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  }
  else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);
  }
  else {nonOrderedPostProcessorNames.add(ppName);
  }

}

// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 首先,执行实现 PriorityOrdered 接口的 BeanFactoryPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 接下来,执行实现 Ordered 接口的 BeanFactoryPostProcessors
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {

  orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.
// 最初,执行 没有实现优先级和排序 接口的 BeanFactoryPostProcessors
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {

  nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

}
// todo 执行 BeanFactoryPostProcessor.postProcessBeanFactory()办法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values…
beanFactory.clearMetadataCache();
}
复制代码
获取到所有 BeanDefinitionRegistryPostProcessor 并创建对象,首先,执行 PriorityOrdered 接口,其次,执行 Ordered 接口,最初,执行没有实现优先级 接口,都会执行 invokeBeanDefinitionRegistryPostProcessors()办法和 invokeBeanFactoryPostProcessors()办法。

3.1.1 invokeBeanDefinitionRegistryPostProcessors()
private static void invokeBeanDefinitionRegistryPostProcessors(

  Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {

for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {

  StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
        .tag("postProcessor", postProcessor::toString);
  // todo 外围,配置类的后置处理器在此解析配置类
  postProcessor.postProcessBeanDefinitionRegistry(registry);
  postProcessBeanDefRegistry.end();

}
}
复制代码
在这里会执行 BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry 办法。

3.1.2 invokeBeanFactoryPostProcessors()
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

private static void invokeBeanFactoryPostProcessors(

  Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

for (BeanFactoryPostProcessor postProcessor : postProcessors) {

  StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
        .tag("postProcessor", postProcessor::toString);
  // todo
  postProcessor.postProcessBeanFactory(beanFactory);
  postProcessBeanFactory.end();

}
}
复制代码
在这里,入参都是 BeanDefinitionRegistryPostProcessor 类型的,所以会执行 BeanDefinitionRegistryPostProcessor.postProcessBeanFactory 办法。

3.1.3
接下来,获取到所有 BeanFactoryPostProcessor 并创建对象,首先,执行 PriorityOrdered 接口,其次,执行 Ordered 接口,最初,执行没有实现优先级 接口,都会执行 invokeBeanFactoryPostProcessors()办法。

本次入参是 BeanFactoryPostProcessor 对象,所以会执行 BeanFactoryPostProcessor.postProcessBeanFactory()办法。

3.1.4 beanFactory.getBeanNamesForType()
spring 中如何依据类型获取所有的组件?
DefaultListableBeanFactory#getBeanNamesForType():

@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {

  // todo
  return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);

}

}
复制代码
// 获取某一个组件 在容器中的名字
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<>();

// Check all bean definitions.
// 因为 Spring 没有 class-bean 的对应信息,只能遍历所有的 beanName 拿出他们所有的 beanName 的定义信息,再看是否指定的类型
// 只有在这里 bean 实例还未创立的时候,能力应用后置处理器干涉 bean 的类型
for (String beanName : this.beanDefinitionNames) {

  // Only consider bean as eligible if the bean name is not defined as alias for some other bean.
  if (!isAlias(beanName)) {
     try {RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        // Only check bean definition if it is complete.
        if (!mbd.isAbstract() && (allowEagerInit ||
              (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
                    !requiresEagerInitForType(mbd.getFactoryBeanName()))) {boolean isFactoryBean = isFactoryBean(beanName, mbd);
           BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
           boolean matchFound = false;
           // containsSingleton(beanName) 是否曾经创立单例对象
           boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));
           boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit());
           if (!isFactoryBean) {if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
                 // 是否类型匹配
                 matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
              }
           }
           else {
              if (includeNonSingletons || isNonLazyDecorated ||
                    (allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
                 // 是否类型匹配
                 matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
              }
              if (!matchFound) {
                 // In case of FactoryBean, try to match FactoryBean instance itself next.
                 beanName = FACTORY_BEAN_PREFIX + beanName;
                 if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                 }
              }
           }
           if (matchFound) {result.add(beanName);
           }
        }
     }
     catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {if (allowEagerInit) {throw ex;}
        // Probably a placeholder: let's ignore it for type matching purposes.
        LogMessage message = (ex instanceof CannotLoadBeanClassException ?
              LogMessage.format("Ignoring bean class loading failure for bean'%s'", beanName) :
              LogMessage.format("Ignoring unresolvable metadata in bean definition'%s'", beanName));
        logger.trace(message, ex);
        // Register exception, in case the bean was accidentally unresolvable.
        onSuppressedException(ex);
     }
     catch (NoSuchBeanDefinitionException ex) {// Bean definition got removed while we were iterating -> ignore.}
  }

}

// Check manually registered singletons too.
for (String beanName : this.manualSingletonNames) {

  try {
     // In case of FactoryBean, match object created by FactoryBean.
     if (isFactoryBean(beanName)) {if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {result.add(beanName);
           // Match found for this bean: do not match FactoryBean itself anymore.
           continue;
        }
        // In case of FactoryBean, try to match FactoryBean itself next.
        beanName = FACTORY_BEAN_PREFIX + beanName;
     }
     // Match raw bean instance (might be raw FactoryBean).
     if (isTypeMatch(beanName, type)) {result.add(beanName);
     }
  }
  catch (NoSuchBeanDefinitionException ex) {
     // Shouldn't happen - probably a result of circular reference resolution...
     logger.trace(LogMessage.format("Failed to check manually registered singleton with name'%s'", beanName), ex);
  }

}

return StringUtils.toStringArray(result);
}
复制代码
次要步骤:

拿到所有组件的名字,beanDefinitionNames
遍历每一个组件名字
再去 BeanDefinitionMap 中找 bean 的定义信息
从定义信息中获取组件的类型
看这个类型是否匹配
3.2 registerBeanPostProcessors(beanFactory)
注册所有 bean 的后置处理器,PostProcessorRegistrationDelegate#registerBeanPostProcessors():

public static void registerBeanPostProcessors(

  ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-pro…

// 获取到容器中所有的 BeanPostProcessor,Bean 的后置处理器
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {

  // 获取所有实现了 PriorityOrdered 接口
  if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
     priorityOrderedPostProcessors.add(pp);
     if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
     }
  }
  else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);
  }
  else {nonOrderedPostProcessorNames.add(ppName);
  }

}

// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先,注册实现了 PriorityOrdered 接口的 BeanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// Next, register the BeanPostProcessors that implement Ordered.
// 接下来,注册实现了 Ordered 接口的 BeanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {

  BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  orderedPostProcessors.add(pp);
  if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
  }

}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// Now, register all regular BeanPostProcessors.
// 最初,注册了一般的 BeanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {

  BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  nonOrderedPostProcessors.add(pp);
  if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
  }

}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

// Finally, re-register all internal BeanPostProcessors.
// 最初,注册所有外部的 BeanPostProcessors
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);

// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 从新注册一下 ApplicationListenerDetector 这个后置处理器
// 把 它放到后置处理器的最初一个地位
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
复制代码
这个步骤,将 bean 的后置处理器 BeanPostProcessor、MergedBeanDefinitionPostProcessor、SmartInstantiationAwareBeanPostProcessor、InstantiationAwareBeanPostProcessor 都注册并初始话实例。

3.3 registerListeners()
这个外围是注册监听器事件,这个咱们前面再说,明天次要阐明 SmartInstantiationAwareBeanPostProcessor.predictBeanType()干涉 bean 的类型。

/**

  • Add beans that implement ApplicationListener as listeners.
  • Doesn’t affect other listeners, which can be added without being beans.
  • 多播器 和监听器 是观察者模式,外面蕴含了所有的监听器
    */

protected void registerListeners() {

// 获取 ApplicationListener 在 ioc 容器中注册的 bean 的名字
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {

  // 获取所有的监听器,并保留他们的名字在
  getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);

}

}
复制代码
也会执行 getBeanNamesForType()办法,后面咱们简略剖析过,咱们间接来到:AbstractAutowireCapableBeanFactory#predictBeanType 办法:

@Override
@Nullable
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>… typesToMatch) {
Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
// Apply SmartInstantiationAwareBeanPostProcessors to predict the
// eventual type after a before-instantiation shortcut.
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {

  boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class;
  // todo 执行 SmartInstantiationAwareBeanPostProcessor.predictBeanType 办法
  for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {Class<?> predicted = bp.predictBeanType(targetType, beanName);
     if (predicted != null &&
           (!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) {return predicted;}
  }

}
return targetType;
}
复制代码
在 3.1 节中 执行 Bean 工厂的后置处理器的时候,hasInstantiationAwareBeanPostProcessors()为 false, 所以进入不了这个办法,起因是因为在 invokeBeanFactoryPostProcessors()办法的时候,BeanPostProcessor 在容器中还没有,所以不会执行。

然而,registerListeners()在 registerBeanPostProcessors()办法之后,所以能够执行这个办法,也就是 SmartInstantiationAwareBeanPostProcessor.predictBeanType()干涉 bean 的组件类型。

3.4 finishBeanFactoryInitialization()
实现 BeanFactory 初始化(工厂外面所有的组件都好了)。beanFactory.preInstantiateSingletons()-> getBean(beanName)->doGetBean->createBean

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

  throws BeanCreationException {


try {

  // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  // todo 提前给咱们一个机会,去返回组件的代理对象
  Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  if (bean != null) {return bean;}

}

try {

  // todo 创建对象
  Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  if (logger.isTraceEnabled()) {logger.trace("Finished creating instance of bean'" + beanName + "'");
  }
  return beanInstance;

}

}
复制代码
3.4.1 resolveBeforeInstantiation(beanName, mbdToUse)
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {

  // Make sure bean class is actually resolved at this point.
  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {Class<?> targetType = determineTargetType(beanName, mbd);
     if (targetType != null) {// todo InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()办法
        bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
        if (bean != null) {bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        }
     }
  }
  mbd.beforeInstantiationResolved = (bean != null);

}
return bean;
}
复制代码
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {

  // todo  执行
  Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
  if (result != null) {return result;}

}
return null;
}
复制代码
在这里执行 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()办法。如果该办法返回 true, 则间接执行 applyBeanPostProcessorsAfterInitialization()办法:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)

  throws BeansException {

Object result = existingBean;
// todo 执行所有 BeanPostProcessor.postProcessAfterInitialization()办法
// 所有的 BeanPostProcessor 类型
for (BeanPostProcessor processor : getBeanPostProcessors()) {

  Object current = processor.postProcessAfterInitialization(result, beanName);
  if (current == null) {return result;}
  result = current;

}
return result;
}
复制代码
在这里执行所有 BeanPostProcessor.postProcessAfterInitialization()办法。

接下来,咱们看一下 doCreateBean 办法。

3.4.2 doCreaeBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

  throws BeanCreationException {

// Instantiate the bean.
BeanWrapper instanceWrapper = null;
// 是否单例
if (mbd.isSingleton()) {

  instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);

}
if (instanceWrapper == null) {

  // todo 创立 Bean 实例,默认应用无参结构器创立的对象,组件的实例就创立了
  instanceWrapper = createBeanInstance(beanName, mbd, args);

}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {

  mbd.resolvedTargetType = beanType;

}

// Allow post-processors to modify the merged bean definition.
// MergedBeanDefinitionPostProcessor 后置处理器再来批改下 BeanDefinition 信息
synchronized (mbd.postProcessingLock) {

  if (!mbd.postProcessed) {
     try {// todo 执行 MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()办法
        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
     }
     catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,
              "Post-processing of merged bean definition failed", ex);
     }
     mbd.postProcessed = true;
  }

}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 提前裸露 单实例 bean 专门来解决循坏援用的问题
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&

     isSingletonCurrentlyInCreation(beanName));

if (earlySingletonExposure) {

  if (logger.isTraceEnabled()) {
     logger.trace("Eagerly caching bean'" + beanName +
           "'to allow for resolving potential circular references");
  }
  // 增加
  // 三级缓存中 Bean 也会被后置解决来加强
  addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

}

// Initialize the bean instance.
Object exposedObject = bean;
try {

  // todo 对象中的每个属性赋值
  populateBean(beanName, mbd, instanceWrapper);
  // todo 初始化 Bean
  exposedObject = initializeBean(beanName, exposedObject, mbd);

}

return exposedObject;
}
复制代码
3.4.2.1 createBeanInstance(beanName, mbd, args)
创立 bean 实例,默认应用无参结构器。

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 创立 bean 的类型
Class<?> beanClass = resolveBeanClass(mbd, beanName);

// Candidate constructors for autowiring?
// todo 候选的结构器 SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()
// 后置处理器有机会在这个决定以后 bean 应用哪个结构器
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||

     mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  // 结构器的形式主动注入与对象创立
  return autowireConstructor(beanName, mbd, ctors, args);

}

// Preferred constructors for default construction?
// 应用默认的本人设置的高优先级的结构器
ctors = mbd.getPreferredConstructors();
if (ctors != null) {

  return autowireConstructor(beanName, mbd, ctors, null);

}

// No special handling: simply use no-arg constructor.
// 默认应用无参结构器为以后组件创建对象
return instantiateBean(beanName, mbd);
}
复制代码
在 determineConstructorsFromBeanPostProcessors 办法中能够决定应用结构器。

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)

  throws BeansException {

if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {

  for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {// todo 执行 SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()办法
     Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
     if (ctors != null) {return ctors;}
  }

}
return null;
}
复制代码
在这里执行 SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()办法。

3.4.2.2 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
// todo 执行 MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()办法
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {

  processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);

}
}
复制代码
在这里执行 MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()办法。

3.4.2.3 populateBean(beanName, mbd, instanceWrapper)
对每个属性进行赋值操作。

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

// 属性赋值之前,后置处理器能够提前准备些货色
// @AutoWired 赋值也在这里 AutowiredAnnotationBeanPostProcessor(间接返回 true 没有其余的解决),能够中断初始化行为
//
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {

  for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {// todo 执行 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() 办法
     if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {return;}
  }

} // 以上的后置处理器能够中断上面的初始化行为

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {

  if (pvs == null) {
     // xml 中 property 标签指定的
     pvs = mbd.getPropertyValues();}
  // 注解版的属性赋值 后置处理器解决属性(真正的主动拆卸)for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {// todo 执行 InstantiationAwareBeanPostProcessor.postProcessProperties() 办法
     PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
     if (pvsToUse == null) {if (filteredPds == null) {filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
        if (pvsToUse == null) {return;}
     }
     pvs = pvsToUse; //  封装了以后 bean 的所有属性名和值,能够由后置处理器解决失去
  }

}

if (pvs != null) {// 把以前解决好的 PropertyValues 给 bean 外面设置一下,次要是下面步骤没有给 bean 外面设置的属性

  // xml 版 的所有配置会来到这里 给属性赋值
  applyPropertyValues(beanName, mbd, bw, pvs);

}
}
复制代码
这里,会执行 2 个后置处理器的办法:

执行 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() 办法
执行 InstantiationAwareBeanPostProcessor.postProcessProperties() 办法
3.4.2.4 initializeBean(beanName, exposedObject, mbd)
对 bean 进行初始化操作。

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {

  AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);
     return null;
  }, getAccessControlContext());

}
else {

  // 组件有 Aware 接口,先 Aware; BeanNameAware BeanClassLoaderAware BeanFactoryAware
  invokeAwareMethods(beanName, bean);

}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {

  // todo 执行后置处理器的 BeforeInitialization,能够扭转之前创立的 bean 实例
  wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

}

try {

  // todo 执行初始化办法 实现 InitializingBean 的接口
  invokeInitMethods(beanName, wrappedBean, mbd);

}
catch (Throwable ex) {

  throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),
        beanName, "Invocation of init method failed", ex);

}
if (mbd == null || !mbd.isSynthetic()) {

  // todo 执行后置处理器的  postProcessAfterInitialization
  wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

}

return wrappedBean;
}
复制代码
在这里,执行三个后置处理器的办法:

执行所有 BeanPostProcessor.postProcessBeforeInitialization()办法
实现 InitializingBean 的接口,执行初始化办法实现 InitializingBean.afterPropertiesSet() 办法
执行所有 BeanPostProcessor.postProcessAfterInitialization()办法
到此,bean 生命周期的所有后置处理器办法的执行机会曾经全副展现进去

退出移动版