认识Spring中的BeanFactoryPostProcessor

2024-06-11 00:28

本文主要是介绍认识Spring中的BeanFactoryPostProcessor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

先看下AI的介绍

在Spring 5.3.x中,BeanFactoryPostProcessor是一个重要的接口,用于在Spring IoC容器实例化任何bean之前,读取bean的定义(配置元数据),并可能对其进行修改。以下是关于BeanFactoryPostProcessor的详细介绍:1. 接口定义与功能
接口定义:BeanFactoryPostProcessor是Spring提供的一个接口,它允许用户自定义逻辑以修改或扩展容器内部的功能。
功能:在BeanFactory实例化之后、其他Bean被创建之前,执行一些自定义的修改或增强操作。这包括修改BeanDefinition(bean的定义信息),如修改属性、添加或删除bean等。
2. 使用方法
实现接口:要使用BeanFactoryPostProcessor,你需要创建一个类来实现这个接口,并重写其中的postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)方法。
注册:将你的BeanFactoryPostProcessor实现注册为Spring容器中的一个bean。这通常可以通过XML配置文件、Java配置类或注解(如@Bean)来完成。
3. 子接口BeanDefinitionRegistryPostProcessor
定义:BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的一个子接口,它添加了一个额外的方法postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)。
功能:除了可以修改BeanDefinition之外,它还可以注册新的bean定义到容器中。
4. 执行顺序
如果有多个BeanFactoryPostProcessor或BeanDefinitionRegistryPostProcessor,可以通过设置order属性或实现Ordered接口来定义它们的执行顺序。
5. 示例
示例代码可能包括一个实现BeanFactoryPostProcessor接口的类,以及一个将其注册为Spring bean的配置类或注解。这个类中的postProcessBeanFactory方法会包含自定义的修改或增强逻辑。
6. 与其他接口的区别
BeanFactoryPostProcessor和BeanPostProcessor都是Spring初始化bean时对外暴露的扩展点,但它们的作用和使用场景不同。BeanFactoryPostProcessor主要关注于修改或增强BeanFactory和BeanDefinition,而BeanPostProcessor则关注于Bean实例化前后的操作。
7. 总结
BeanFactoryPostProcessor是Spring框架中一个非常有用的接口,它允许你在Spring IoC容器实例化bean之前,对bean的定义进行自定义的修改或增强。通过实现这个接口并注册你的实现类,你可以扩展Spring容器的功能,满足更复杂的应用需求。

根据BeanFactoryPostProcessor的介绍,创建几个测试类:
A类
通过扫描增加,BeanFactoryPostProcessor 实现类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;/**
* 简单实现
*/
@Component
public class A implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("A scan");}
}

B类
通过扫描增加,实现BeanFactoryPostProcessor, PriorityOrdered类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class B implements BeanFactoryPostProcessor, PriorityOrdered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("B scan, priorityOrdered 0");}@Overridepublic int getOrder() {return 0;}
}

B1类
通过扫描增加,实现BeanFactoryPostProcessor, PriorityOrdered类,排序靠后

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class B1 implements BeanFactoryPostProcessor, PriorityOrdered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("B1 scan, priorityOrdered 1");}@Overridepublic int getOrder() {return 1;}
}

C类
通过扫描增加,实现BeanFactoryPostProcessor, Ordered 类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class C implements BeanFactoryPostProcessor, Ordered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("C scan, Ordered 0");}@Overridepublic int getOrder() {return 0;}
}

C1类
通过扫描增加,实现BeanFactoryPostProcessor, Ordered 类,排序靠后

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;@Component
public class C1 implements BeanFactoryPostProcessor, Ordered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("C1 scan, Ordered 1");}@Overridepublic int getOrder() {return 1;}
}

D类
通过扫描增加,实现BeanFactoryPostProcessor的类,注解@Order

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Component
@Order(1)
public class D implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("D scan, @Ordered 1");}}

E类
在测试类中,通过api增加

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;public class E implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("E parent api add");}}

F类
普通Bean


package org.springframework.example.BFPP;import org.springframework.stereotype.Component;@Component
public class F {private String name;@Overridepublic String toString() {return "F{" +"name='" + name + '\'' +'}';}
}

F1类
修改的Bean

package org.springframework.example.BFPP;import org.springframework.stereotype.Component;@Component
public class F1 {private String name;@Overridepublic String toString() {return "F1{" +"name='" + name + '\'' +'}';}
}

G类
其中修改了F的BeanDefinition

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.stereotype.Component;@Component
public class G implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) beanFactory.getBeanDefinition("f");beanDefinition.setBeanClass (F1.class);}
}

H类
扫描增加,实现了BeanDefinitionRegistryPostProcessor 的类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;@Component
public class H implements BeanDefinitionRegistryPostProcessor  {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("H sub-parent");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("H sub");}
}

I类
在J类中增加,实现了BeanDefinitionRegistryPostProcessor 的类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;public class I implements BeanDefinitionRegistryPostProcessor  {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("I sub-parent");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("I sub");}
}

J类
通过扫描增加,实现了BeanDefinitionRegistryPostProcessor 的类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;@Component
public class J implements BeanDefinitionRegistryPostProcessor  {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("J sub-parent");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("J sub add BFPP I");BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(I.class);registry.registerBeanDefinition("i", builder.getBeanDefinition());}
}

K类
通过扫描增加,实现了BeanDefinitionRegistryPostProcessor 、PriorityOrdered 的类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class K implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("k sub-parent priorityOrdered 0");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("K sub priorityOrdered 0");}@Overridepublic int getOrder() {return 0;}
}

K1类
通过扫描增加,实现了BeanDefinitionRegistryPostProcessor 、PriorityOrdered 的类,排序靠后

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class K1 implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("k1 sub-parent priorityOrdered 1");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("K1 sub priorityOrdered 1");}@Overridepublic int getOrder() {return 1;}
}

L类
通过扫描增加,实现了BeanDefinitionRegistryPostProcessor 、Ordered 的类

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;@Component
public class L implements BeanDefinitionRegistryPostProcessor, Ordered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("L sub-parent Ordered 0");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("L sub Ordered 0");}@Overridepublic int getOrder() {return 0;}
}

L1类
通过扫描增加,实现了BeanDefinitionRegistryPostProcessor 、Ordered 的类,排序靠后

package org.springframework.example.BFPP;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;@Component
public class L1 implements BeanDefinitionRegistryPostProcessor, Ordered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("L1 sub-parent Ordered 1");}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("L1 sub Ordered 1");}@Overridepublic int getOrder() {return 1;}
}

BFPPTest测试类

package org.springframework.example.BFPP;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class BFPPTest {public static void main(String[] args) {AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();annotationConfigApplicationContext.scan("org.springframework.example.BFPP");annotationConfigApplicationContext.addBeanFactoryPostProcessor(new E());annotationConfigApplicationContext.addBeanFactoryPostProcessor(new E1());annotationConfigApplicationContext.refresh();System.out.println(annotationConfigApplicationContext.getBean("f"));}
}

运行结果

E1 sub api add
K sub priorityOrdered 0
K1 sub priorityOrdered 1
L sub Ordered 0
L1 sub Ordered 1
H sub
J sub add BFPP I
I sub
E1 sub parent api add
k sub-parent priorityOrdered 0
k1 sub-parent priorityOrdered 1
L sub-parent Ordered 0
L1 sub-parent Ordered 1
H sub-parent
J sub-parent
I sub-parent
E parent api add
B scan, priorityOrdered 0
B1 scan, priorityOrdered 1
C scan, Ordered 0
C1 scan, Ordered 1
A scan
D scan, @Ordered 1
F1{name='null'}

可以看到执行顺序是:
1、执行实现了BeanDefinitionRegistryPostProcessor接口,通过addBeanFactoryPostProcessor 添加的类
2、执行实现了BeanDefinitionRegistryPostProcessor接口、PriorityOrdered接口的类
3、执行实现了BeanDefinitionRegistryPostProcessor接口、Ordered 接口的类
4、执行剩余实现了BeanDefinitionRegistryPostProcessor接口的类,以及后置处理中新增的BeanDefinitionRegistryPostProcessor类
5、执行实现了BeanDefinitionRegistryPostProcessor接口类的父类BeanFactoryPostProcessor的postProcessBeanFactory方法
6、执行实现了父类BeanFactoryPostProcessor接口,通过addBeanFactoryPostProcessor 添加的类
7、执行实现了父类BeanFactoryPostProcessor接口、PriorityOrdered接口的类
8、执行实现了父类BeanFactoryPostProcessor接口、Ordered 接口的类
9、其他剩余实现了BeanFactoryPostProcessor接口的类

接着来分析一下源码:
BeanFactoryPostProcessor的处理也是在AbstractApplicationContext的refresh内invokeBeanFactoryPostProcessors中,继续跟踪直到PostProcessorRegistrationDelegate–>invokeBeanFactoryPostProcessors

发现没有,跟前面的BeanPostProcessor的处理在同一个类中

	/*** 调用BeanFactory 后置处理器* @param beanFactory* @param beanFactoryPostProcessors*/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-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22// Invoke BeanDefinitionRegistryPostProcessors first, if any.//存放所有已经处理的Bean名称,避免重复处理Set<String> processedBeans = new HashSet<>();//先处理beanFactory是BeanDefinitionRegistry类型的,BeanDefinitionRegistry 用来注册和管理BeanDefinition//在spring中一般都是DefaultListableBeanFactoryif (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;//存放常规的BeanFactoryPostProcessorList<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();//存放BeanDefinitionRegistryPostProcessor类型的BeanFactoryPostProcessor//其是BeanFactoryPostProcessor的子类List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {//先处理BeanDefinitionRegistryPostProcessor类型的BeanFactoryPostProcessorif (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;registryProcessor.postProcessBeanDefinitionRegistry(registry);registryProcessors.add(registryProcessor);}else {//处理常规的BeanFactoryPostProcessorregularPostProcessors.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.//存放当前执行的BeanDefinitionRegistryPostProcessorList<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.//获取BeanDefinitionRegistryPostProcessor类型的BeanFactoryPostProcessor 名称String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {//处理实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessorif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}//排序sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);//里面循环调用BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());//清空当前执行的BeanDefinitionRegistryPostProcessor列表,因为后面还要用currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.//处理实现了Ordered接口的BeanDefinitionRegistryPostProcessorpostProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {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.//最后处理其他的BeanDefinitionRegistryPostProcessor,直到没有新的BeanDefinitionRegistryPostProcessor//循环处理,因为在BeanDefinitionRegistryPostProcessor中可能会注册新的BeanDefinitionRegistryPostProcessorboolean 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);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();}// Now, invoke the postProcessBeanFactory callback of all processors handled so far.//调用所有已处理的BeanDefinitionRegistryPostProcessors和BeanFactoryPostProcessors的postProcessBeanFactory方法//这段内部调用的是BeanDefinitionRegistryPostProcessor父类的postProcessBeanFactory方法invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);}else {// Invoke factory processors registered with the context instance.//如果beanFactory不是一个BeanDefinitionRegistry,直接调用所有的bean工厂后处理器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!//查找所有实现了父类BeanFactoryPostProcessor接口的beanString[] postProcessorNames =beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,// Ordered, and the rest.//存放priorityOrdered的BeanFactoryPostProcessorList<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();//存放ordered的BeanFactoryPostProcessorList<String> orderedPostProcessorNames = new ArrayList<>();//存放没有实现priorityOrdered和ordered的BeanFactoryPostProcessorList<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的BeanFactoryPostProcessorsortPostProcessors(priorityOrderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);// Next, invoke the BeanFactoryPostProcessors that implement Ordered.//处理实现ordered的BeanFactoryPostProcessorList<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.//处理没有实现priorityOrdered和ordered的BeanFactoryPostProcessorList<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String postProcessorName : nonOrderedPostProcessorNames) {nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);// Clear cached merged bean definitions since the post-processors might have// modified the original metadata, e.g. replacing placeholders in values...//清空缓存的合并bean定义,因为后处理器可能修改了原始的元数据,例如替换值中的占位符beanFactory.clearMetadataCache();}

Debug 启动,能够看到beanFactory 是 DefaultListableBeanFactory,所以进入BeanDefinitionRegistry部分,此时的beanFactoryPostProcessors 只有E、E1,这两个是通过BFPPTest类中的addBeanFactoryPostProcessor增加,会在invokeBeanFactoryPostProcessors中最先获取。
在这里插入图片描述

在这里插入图片描述

继续往下执行,随后会判断postProcessor类型是否是BeanDefinitionRegistryPostProcessor类型,如果是会最先得到处理,调用其postProcessBeanDefinitionRegistry方法。

所以E1类是实现了BeanDefinitionRegistryPostProcessor接口,并且通过api增加,就在这里最先打印日志。

继续执行,来到了处理实现了PriorityOrdered接口的类
在这里插入图片描述

继续执行,下面来处理实现了Ordered接口的类
在这里插入图片描述

继续执行到了,循环处理部分,此处会处理在J类中增加的I类
在这里插入图片描述

继续执行,开始处理实现了BeanDefinitionRegistryPostProcessor接口父类的postProcessBeanFactory方法
在这里插入图片描述

在这里插入图片描述
下一步接口处理通过最开始采集到的regularPostProcessors中的BeanFactoryPostProcessor,此时这个里面只有一个E类,我们通过api接口添加
在这里插入图片描述

到这里为止,BeanDefinitionRegistryPostProcessor接口的类已经处理完毕

接口处理BeanFactoryPostProcessor接口的类,会把实现了BeanDefinitionRegistryPostProcessor接口的类也找出来,因为BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子类
在这里插入图片描述

后面是同样的操作,先处理实现了PriorityOrdered接口的类,再处理Ordered的类,最后出来其他类。加了@Order注解的类,是当做没有实现排序类处理,所以加@Order注解对于排序在这里同样是没用的,跟BeanPostProcessor一样
在这里插入图片描述

最后,清除缓存的合并Bean definitions,为什么要清除?好像是在并发环境下会获取到老的Bean。见:https://github.com/spring-projects/spring-framework/issues/18841

至于对BeanDefinition的修改,在G类里面将F对应的Bean类修改为F1,最后从容器中获取的Bean也是确实变成了F1。
在这里插入图片描述


作者其他文章推荐:
基于Spring Boot 3.1.0 系列文章

  1. Spring Boot 源码阅读初始化环境搭建
  2. Spring Boot 框架整体启动流程详解
  3. Spring Boot 系统初始化器详解
  4. Spring Boot 监听器详解
  5. Spring Boot banner详解
  6. Spring Boot 属性配置解析
  7. Spring Boot 属性加载原理解析
  8. Spring Boot 异常报告器解析
  9. Spring Boot 3.x 自动配置详解

这篇关于认识Spring中的BeanFactoryPostProcessor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1049695

相关文章

springboot健康检查监控全过程

《springboot健康检查监控全过程》文章介绍了SpringBoot如何使用Actuator和Micrometer进行健康检查和监控,通过配置和自定义健康指示器,开发者可以实时监控应用组件的状态,... 目录1. 引言重要性2. 配置Spring Boot ActuatorSpring Boot Act

使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)

《使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)》在现代软件开发中,处理JSON数据是一项非常常见的任务,无论是从API接口获取数据,还是将数据存储为JSON格式,解析... 目录1. 背景介绍1.1 jsON简介1.2 实际案例2. 准备工作2.1 环境搭建2.1.1 添加

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

java如何分布式锁实现和选型

《java如何分布式锁实现和选型》文章介绍了分布式锁的重要性以及在分布式系统中常见的问题和需求,它详细阐述了如何使用分布式锁来确保数据的一致性和系统的高可用性,文章还提供了基于数据库、Redis和Zo... 目录引言:分布式锁的重要性与分布式系统中的常见问题和需求分布式锁的重要性分布式系统中常见的问题和需求

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

《SpringBoot基于MyBatis-Plus实现LambdaQuery查询的示例代码》MyBatis-Plus是MyBatis的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方... 目录引言基础环境配置依赖配置(Maven)application.yml 配置表结构设计demo_st

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

JAVA中整型数组、字符串数组、整型数和字符串 的创建与转换的方法

《JAVA中整型数组、字符串数组、整型数和字符串的创建与转换的方法》本文介绍了Java中字符串、字符数组和整型数组的创建方法,以及它们之间的转换方法,还详细讲解了字符串中的一些常用方法,如index... 目录一、字符串、字符数组和整型数组的创建1、字符串的创建方法1.1 通过引用字符数组来创建字符串1.2

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python