Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解

简介: Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解

文章目录

Spring源码系列:

前言

正文

方法1:prepareBeanFactory

方法2:postProcessBeanFactory

方法3:invokeBeanFactoryPostProcessors

方法4:getBeanFactoryPostProcessors()

方法5:invokeBeanFactoryPostProcessors

方法6:sortPostProcessors

总结

Spring源码系列:

Spring IOC源码:简单易懂的Spring IOC 思路介绍

Spring IOC源码:核心流程介绍

Spring IOC源码:ApplicationContext刷新前准备工作

Spring IOC源码:obtainFreshBeanFactory 详解(上)

Spring IOC源码:obtainFreshBeanFactory 详解(中)

Spring IOC源码:obtainFreshBeanFactory 详解(下)

Spring IOC源码:<context:component-scan>源码详解

Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解

Spring IOC源码:registerBeanPostProcessors 详解

Spring IOC源码:实例化前的准备工作

Spring IOC源码:finishBeanFactoryInitialization详解

Spring IoC源码:getBean 详解

Spring IoC源码:createBean( 上)

Spring IoC源码:createBean( 中)

Spring IoC源码:createBean( 下)

Spring IoC源码:finishRefresh 完成刷新详解

前言

前面篇幅介绍了Bean配置的解析过程,包括注解、xml配置文件的解析。下面进入refresh方法中另一个重要的节点,即BeanFactoryPostProcessor的注册及其执行过程。

正文

进入refresh,前面篇幅已经介绍了obtainFreshBeanFactory(),接下来进入

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
      // 容器刷新前准备工作
      prepareRefresh();
      // Tell the subclass to refresh the internal bean factory.
      //创建Bean工厂,解析配置
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      // bean工厂准备工作
      prepareBeanFactory(beanFactory);
      try {
        //拓展接口,留给子类进行实现拓展
        postProcessBeanFactory(beanFactory);
        // 注册执行,BeanFactoryPostProcessor
        invokeBeanFactoryPostProcessors(beanFactory);
        // 注册创建BeanPostProcessor
        registerBeanPostProcessors(beanFactory);
        // 这个方法主要作用就是使用国际化,定制不同的消息文本,比如定义了一个Person的Bean,它有name属性,我们需要在不同的国家展示对应国家所在语言名称,这时候就可以使用国际化了。
        initMessageSource();
        // Initialize event multicaster for this context.
        //初始化应用事件广播器
        initApplicationEventMulticaster();
        // Initialize other special beans in specific context subclasses.
        //拓展接口,留给子类进行实现拓展,springboot就对该方法进行了处理
        onRefresh();
        // Check for listener beans and register them.
        //将内部的、以及我们自定义的监听器添加到缓存中,为后续逻辑处理做准备。还有添加事件源到缓存中。
        registerListeners();
        // Instantiate all remaining (non-lazy-init) singletons.
        //实例化剩下非懒加载的Bean
        finishBeanFactoryInitialization(beanFactory);
        // Last step: publish corresponding event.
        //使用应用事件广播器推送上下文刷新完毕事件(ContextRefreshedEvent )到相应的监听器。
        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();
      }
    }
  }

prepareBeanFactory(beanFactory),见方法1详解

postProcessBeanFactory(beanFactory),见方法2详解

invokeBeanFactoryPostProcessors(beanFactory),见方法3详解

方法1:prepareBeanFactory

  protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 为当前Bean工厂设置类加载器
    beanFactory.setBeanClassLoader(getClassLoader());
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    //添加BeanPostProcessor后置处理器
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    //跳过以下6个属性的自动注入
    //因为在ApplicationContextAwareProcessor后置处理器中通过setter注入
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    /**
     * 在Spring自动装配的时候如果一个接口有多个实现类,并且都已经放到IOC中去了,
     * 那么自动装配的时候就会出异常,因为spring不知道把哪个实现类注入进去,
     * 但是如果我们自定义一个类,然后实现BeanFactoryPostProcessor接口
     * 在该阶段调用这个方法,如果哪个地方要自动注入这个类型的对象的话,那么就注入进去我们指定的对象
    */
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    // Register early post-processor for detecting inner beans as ApplicationListeners.
    注册事件监听器
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    //如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ,则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入AspectJ的目的。
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
    // 将以下Bean添加到一级缓存中
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
  }

方法2:postProcessBeanFactory

  protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  }

这个方法没有实现内容,为拓展接口,留给子类实现。我们可以看到这个方法的参数为bean工厂对象,意味着我们可以往该工厂中添加后置处理器或者添加忽略类,在后续注入中跳过。也可以往三级缓存中添加信息。

例如:

  protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    if (this.servletContext != null) {
      beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
      beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    }
    WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
  }

方法3:invokeBeanFactoryPostProcessors

  protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //执行BeanFactoryPostProcessors
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
    // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
  }

getBeanFactoryPostProcessors(),见方法4详解

invokeBeanFactoryPostProcessors(),见方法5详解

方法4:getBeanFactoryPostProcessors()

  public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
    return this.beanFactoryPostProcessors;
  }

我们看到这里是直接返回当前上下文的beanFactoryPostProcessors集合,默认情况下这里是空的,那我们如何自定义一个后置处理器并且往该集合存放呢?我们可以自定义ClassPathXmlApplicationContext子类,重写上述介绍的方法2postProcessBeanFactory方法,并往beanFactoryPostProcessors添加自定义后置处理器;


创建工厂后置处理器

package controller.main;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    Object teacher = beanFactory.getBean("teacher");
    System.out.println(teacher);
  }
}

自定义ClassPathXmlApplicationContext子类,并添加后置处理器

package controller.main;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyClassPathApplicationContext extends ClassPathXmlApplicationContext {
  public MyClassPathApplicationContext(String path){
    super(path);
  }
  @Override
  protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    this.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
  }
}

启动测试

public class PersonTest {
  public static void main(String[] args) {
    MyClassPathApplicationContext applicationContext=new MyClassPathApplicationContext("application-scan.xml");
    StudentDao zdcDomain = (StudentDao) applicationContext.getBean("studentDao");
    System.out.println(zdcDomain);
  }
}

040bd7286ead3d3e4095881ddeb84709_7c682d4a7e964d21a11e733e0aad4c4e.png

方法5:invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    // 存放BeanDefinitionRegistryPostProcessor类型已经执行过其postProcessBeanDefinitionRegistry方法的beanName
    Set<String> processedBeans = new HashSet<>();
    if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      //存放普通的PostProcessors,就是非BeanDefinitionRegistryPostProcessor类型的
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      //存放BeanDefinitionRegistryPostProcessor类型的处理器
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
      //遍历上下文中的beanFactoryPostProcessors集合,也就是我们在方法4中设置进去的后置处理器集合
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
        if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
          BeanDefinitionRegistryPostProcessor registryProcessor =
              (BeanDefinitionRegistryPostProcessor) postProcessor;
          //执行postProcessBeanDefinitionRegistry方法
          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.
      //获取我们bean工厂中类型为BeanDefinitionRegistryPostProcessor的beanName
      String[] postProcessorNames =
          beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
        //判断是否实现了PriorityOrdered接口
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
          //添加到当前节点中
          currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
          //添加名称到集合中
          processedBeans.add(ppName);
        }
      }
      //排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      //将当前节点的后置处理器添加到registryProcessors集合中
      registryProcessors.addAll(currentRegistryProcessors);
      //执行postProcessBeanDefinitionRegistry方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      //清空当前节点集合
      currentRegistryProcessors.clear();
      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      //重新获取类型为BeanDefinitionRegistryPostProcessor的beanName,为什么这里要重新获取一次,
      //我理解就是上面执行了post ProcessBeanDefinitionRegistry方法,可能存在往bean工厂中添加类型为
      //BeanDefinitionRegistryPostProcessor的BeanDefinition封装对象,所以这里算是更新数据吧
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
        //判断执行过的processedBeans集合中不存在,并且实现了Ordered接口
        if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
          //添加到当前节点中
          currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
          //添加名称到已执行集合中
          processedBeans.add(ppName);
        }
      }
      //排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      //将当前节点的后置处理器添加到registryProcessors集合中
      registryProcessors.addAll(currentRegistryProcessors);
      //执行postProcessBeanDefinitionRegistry方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);    
      //清空当前节点集合
      currentRegistryProcessors.clear();
      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      boolean reiterate = true;
      while (reiterate) {
        reiterate = false;
        //获取类型BeanDefinitionRegistryPostProcessor的beanName
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        //这里主要获取没有实现PriorityOrdered和Order类的后置处理器
        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);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
      }
      // 执行postProcessBeanFactory(beanFactory)方法
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }
    else {
      // Invoke factory processors registered with the context instance.
      //没有实现BeanDefinitionRegistry接口的,直接执行postProcessBeanFactory(beanFactory)方法
      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }
    // 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.
    //存放实现了PriorityOrdered接口的后置处理器
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    //存放实现了Ordered接口的BeanName
    List<String> orderedPostProcessorNames = new ArrayList<>();
    //存放没有实现了PriorityOrdered和Ordered接口的BeanName
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
      //跳过之前已经执行过的,也就是BeanDefinitionRegistryPostProcessor类型的后置处理器
      if (processedBeans.contains(ppName)) {
        // skip - already processed in first phase above
      }
      //实现PriorityOrdered,添加至集合中
      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
        //getBean方法会从三级缓存获取,取不到会提交调用实例化初始化步骤
        priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
      }
      //实现Ordered,添加至集合中
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
        orderedPostProcessorNames.add(ppName);
      }
      //添加至集合中
      else {
        nonOrderedPostProcessorNames.add(ppName);
      }
    }
    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    //排序并调用postProcessBeanFactory(beanFactory)方法
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    //遍历从bean工厂中获取实例对象,取不到进行实例化操作
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String postProcessorName : orderedPostProcessorNames) {
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //排序并调用postProcessBeanFactory(beanFactory)方法
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    // Finally, invoke all other BeanFactoryPostProcessors.
    遍历从bean工厂中获取实例对象,取不到进行实例化操作
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //排序并调用postProcessBeanFactory(beanFactory)方法
    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();
  }

sortPostProcessors(),见方法6详解’

方法6:sortPostProcessors

private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
    Comparator<Object> comparatorToUse = null;
    if (beanFactory instanceof DefaultListableBeanFactory) {
      comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
    }
    if (comparatorToUse == null) {
      comparatorToUse = OrderComparator.INSTANCE;
    }
    postProcessors.sort(comparatorToUse);
  }

这里我们的比较器为AnnotationAwareOrderComparator,在前面文章中的方法19有设置该比较器。

比较器部分代码如下:

  private int doCompare(Object o1, Object o2, OrderSourceProvider sourceProvider) {
    // 判断o1是否实现了PriorityOrdered接口
    boolean p1 = (o1 instanceof PriorityOrdered);
    // 判断o2是否实现了PriorityOrdered接口
    boolean p2 = (o2 instanceof PriorityOrdered);
    // 1.如果o1实现了PriorityOrdered接口, 而o2没有, 则o1排前面
    if (p1 && !p2) {
      return -1;
    }
    // 2.如果o2实现了PriorityOrdered接口, 而o1没有, 则o2排前面
    else if (p2 && !p1) {
      return 1;
    }
    // 3.如果o1和o2都实现(都没实现)PriorityOrdered接口
    // Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation.
    // 拿到o1的order值, 如果没实现Ordered接口, 值为Ordered.LOWEST_PRECEDENCE
    int i1 = getOrder(o1, sourceProvider);
    // 拿到o2的order值, 如果没实现Ordered接口, 值为Ordered.LOWEST_PRECEDENCE
    int i2 = getOrder(o2, sourceProvider);
    // 4.通过order值(order值越小, 优先级越高)排序
    return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
  }

比较器的逻辑很简单,实现 PriorityOrdered 接口的优先级最高,如果两个对象都实现(都没实现)PriorityOrdered 接口,则根据 order 值(实现 Ordered 接口时,需要实现 getOrder() 方法,返回 order 值)来进行比较,order 值越小,优先级越高。

总结

本篇文章讲解了refresh方法中的prepareBeanFactory、postProcessBeanFactory、invokeBeanFactoryPostProcessors这三个方法。prepareBeanFactory其实就是BeanFactory工厂做一些准备工作,忽略某些值不被其它类所注入,以及添加一些后置处理器等。postProcessBeanFactory方法为拓展接口,提供子类进行拓展实现,我们也讲解了案例,通过编写实现ClassPathXmlApplicationContext子类重写该方法,并往该方法中添加后置处理器。invokeBeanFactoryPostProcessors方法主要是执行后置处理,主要分为两种类型的BeanFactoryPostProcessor,实现接口BeanDefinitionRegistryPostProcessor的和直接实现BeanFactoryPostProcessor接口的,BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的接口实现类。


梳理一下invokeBeanFactoryPostProcessors方法:

1.整个 invokeBeanFactoryPostProcessors 方法围绕两个接口,BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor,其中 BeanDefinitionRegistryPostProcessor 继承了 BeanFactoryPostProcessor 。BeanDefinitionRegistryPostProcessor 主要用来在常规 BeanFactoryPostProcessor 检测开始之前注册其他 Bean 定义,说的简单点,就是 BeanDefinitionRegistryPostProcessor 具有更高的优先级,执行顺序在 BeanFactoryPostProcessor 之前。


2.整个 invokeBeanFactoryPostProcessors 方法操作了 3 种 bean 对象:

入参beanFactoryPostProcessors集合:

这个我们在方法4中有讲解过,主要取的是当前上下文对象,我们可以通过自定义上下文,并往该集合中添加后置处理器。


BeanDefinitionRegistryPostProcessor 接口实现类:

实现了 BeanDefinitionRegistryPostProcessor 接口,并且注册到 Spring IoC容器中。


常规 BeanFactoryPostProcessor 接口实现类:

实现了 BeanFactoryPostProcessor 接口,并且注册到 Spring IoC容器中。


3.该方法中的排序还引用了两个重要的接口PriorityOrdered 和 Ordered,其中 PriorityOrdered 继承了 Ordered,并且 PriorityOrdered 的优先级要高于 Ordered。实现 Ordered 接口需要重写 getOrder 方法,返回一个用于排序的 order 值,order 值的范围为 Integer.MIN_VALUE ~ Integer.MAX_VALUE,order 值越小优先级越高,Integer.MIN_VALUE 拥有最高优先级,而 Integer.MAX_VALUE 则对应的拥有最低优先级。


4.BeanFactoryPostProcessor中的优先级执行顺序如下:


第一优先级:上下文beanFactoryPostProcessors集合中的 BeanDefinitionRegistryPostProcessor,会先调用其 postProcessBeanDefinitionRegistry 方法。

第二优先级:beanFactory工厂中的bean,也就是我们配置文件或者注解所配置的Bean,实现了BeanDefinitionRegistryPostProcessor 、 PriorityOrdered 接口,会调用 postProcessBeanDefinitionRegistry 方法。

第三优先级:beanFactory工厂中的bean,实现BeanDefinitionRegistryPostProcessor 、Ordered 接口,会调用 postProcessBeanDefinitionRegistry 方法。

第四优先级:没有实现PriorityOrdered 或Ordered 接口的 BeanDefinitionRegistryPostProcessor 接口实现类,调用 postProcessBeanDefinitionRegistry 方法。

第五优先级:所有 BeanDefinitionRegistryPostProcessor 接口实现类,调用 postProcessBeanFactory 方法。

第六优先级:入参 beanFactoryPostProcessors 集合中的常规 BeanFactoryPostProcessor,调用 postProcessBeanFactory 方法。

第七优先级:beanFactory工厂中的bean,常规 BeanFactoryPostProcessor 接口实现类,并且实现了 PriorityOrdered 接口,调用 postProcessBeanFactory 方法。

第八优先级:beanFactory工厂中的bean,常规 BeanFactoryPostProcessor 接口实现类,并且实现了 Ordered 接口,调用 postProcessBeanFactory 方法。

第九优先级:没有实现PriorityOrdered 或Ordered 接口的 BeanFactoryPostProcessor 接口实现类,调用 postProcessBeanFactory 方法。


目录
相关文章
|
3天前
|
XML Java 数据格式
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
|
3天前
|
XML Java 数据格式
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)
这篇文章是Spring5框架的实战教程,主题是IOC容器中Bean的集合属性注入,通过XML配置方式。文章详细讲解了如何在Spring中注入数组、List、Map和Set类型的集合属性,并提供了相应的XML配置示例和Java类定义。此外,还介绍了如何在集合中注入对象类型值,以及如何使用Spring的util命名空间来实现集合的复用。最后,通过测试代码和结果展示了注入效果。
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)
|
3天前
|
XML Java 数据格式
Spring5入门到实战------6、IOC容器-Bean管理XML方式(自动装配)
这篇文章是Spring5框架的入门教程,详细讲解了IOC容器中Bean的自动装配机制,包括手动装配、`byName`和`byType`两种自动装配方式,并通过XML配置文件和Java代码示例展示了如何在Spring中实现自动装配。
Spring5入门到实战------6、IOC容器-Bean管理XML方式(自动装配)
|
3天前
|
XML Java 数据格式
Spring5入门到实战------5、IOC容器-Bean管理(三)
这篇文章深入探讨了Spring5框架中IOC容器的高级Bean管理,包括FactoryBean的使用、Bean作用域的设置、Bean生命周期的详细解释以及Bean后置处理器的实现和应用。
Spring5入门到实战------5、IOC容器-Bean管理(三)
|
3天前
|
XML Java 数据格式
Spring5入门到实战------3、IOC容器-Bean管理XML方式(一)
这篇文章详细介绍了Spring框架中IOC容器的Bean管理,特别是基于XML配置方式的实现。文章涵盖了Bean的定义、属性注入、使用set方法和构造函数注入,以及如何注入不同类型的属性,包括null值、特殊字符和外部bean。此外,还探讨了内部bean的概念及其与外部bean的比较,并提供了相应的示例代码和测试结果。
Spring5入门到实战------3、IOC容器-Bean管理XML方式(一)
|
3天前
|
XML Java 数据格式
Spring5入门到实战------2、IOC容器底层原理
这篇文章深入探讨了Spring5框架中的IOC容器,包括IOC的概念、底层原理、以及BeanFactory接口和ApplicationContext接口的介绍。文章通过图解和实例代码,解释了IOC如何通过工厂模式和反射机制实现对象的创建和管理,以及如何降低代码耦合度,提高开发效率。
Spring5入门到实战------2、IOC容器底层原理
|
3天前
|
XML Java 数据格式
Spring5入门到实战------8、IOC容器-Bean管理注解方式
这篇文章详细介绍了Spring5框架中使用注解进行Bean管理的方法,包括创建Bean的注解、自动装配和属性注入的注解,以及如何用配置类替代XML配置文件实现完全注解开发。
Spring5入门到实战------8、IOC容器-Bean管理注解方式
|
3天前
|
XML Java 数据格式
Spring5入门到实战------2、IOC容器底层原理
这篇文章深入探讨了Spring5框架中的IOC容器,包括IOC的概念、底层原理、以及BeanFactory接口和ApplicationContext接口的介绍。文章通过图解和实例代码,解释了IOC如何通过工厂模式和反射机制实现对象的创建和管理,以及如何降低代码耦合度,提高开发效率。
Spring5入门到实战------2、IOC容器底层原理
|
4天前
|
Java Spring 容器
建模底层逻辑问题之以Spring IOC容器为例,使用因果法建模,如何操作
建模底层逻辑问题之以Spring IOC容器为例,使用因果法建模,如何操作
|
6天前
|
XML Dubbo Java
Spring之Ioc容器
该文章主要介绍了Spring框架中的IoC(Inversion of Control,控制反转)容器,包括IoC容器的概念、IoC容器在Spring中的实现以及IoC容器的基础包等内容。
Spring之Ioc容器