invokeBeanFactoryPostProcessors(beanFactory)方法是refresh方法中第5步逻辑,注册 BeanFactoryPostProcessor 处理器,然后实例化并调用 BeanFactoryPostProcessor 处理器的实现。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
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()));
}
}
该方法的所有的核心逻辑都在PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())中封装的,具体逻辑如下:
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 优先执行BeanDefinitionRegistryPostProcessors,将已经执行过的BFPP存储在 processedBeans 中,防止重复执行
Set<String> processedBeans = new HashSet<>();
// 判断 beanFactory 是否是 BeanDefinitionRegistry 类型,即 DefaultListableBeanFactory,实现了 BeanDefinitionRegistry 接口,所以为 true
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
/**
* BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor 两个接口的区别???
* (1) BeanDefinitionRegistryPostProcessor 是 BeanFactoryPostProcessor 的子类
* (2) BeanFactoryPostProcessor 主要是对 BeanFactory 的操作;而 BeanDefinitionRegistryPostProcessor 主要对 BeanDefinition 的操作
*/
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 遍历入参 beanFactoryPostProcessors,将 BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor 接口分开存储到集合中去
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
// 直接执行BeanDefinitionRegistryPostProcessor接口中的postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
} else {
// 普通的 BeanFactoryPostProcessor,添加到 regularPostProcessors 集合中去,用于后续执行 BeanFactoryPostProcessor 接口的 postProcessBeanFactory 方法
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.
// 保存本次要执行的 BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 调用所有实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 实现类
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到 registryProcessors 中,用于最后执行 postProcessBeanFactory 方法
registryProcessors.addAll(currentRegistryProcessors);
// 遍历 currentRegistryProcessors,执行 postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 调用所有实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor 实现类
postProcessorNames = 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 中,用于最后执行 postProcessBeanFactory 方法
registryProcessors.addAll(currentRegistryProcessors);
// 遍历 currentRegistryProcessors,执行 postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 最后,调用所有剩下的 BeanDefinitionRegistryPostProcessors
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 跳过已经执行过的 BeanDefinitionRegistryPostProcessor
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();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用所有 BeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 调用入参 beanFactoryPostProcessors 中的普通 BeanFactoryPostProcessor (不是 BeanDefinitionRegistryPostProcessor 类型) 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// Invoke factory processors registered with the context instance.
// 如果 beanFactory 不归属于 BeanDefinitionRegistry 类型,那么直接执行 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
/************************/
// 1. 到这里为止,入参 beanFactoryPostProcessors 和容器中的所有 BeanDefinitionRegistryPostProcessor 已经全部处理完毕
// 2. 下面开始处理所有的 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)) {
} 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.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
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...
beanFactory.clearMetadataCache();
}
一、BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessors
这个方法的逻辑很长,但只需要重点掌握 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessors,然后方法的逻辑就很容易理解了
1. BeanFactoryPostProcessors
@FunctionalInterface
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessors允许修改BeanFactory的中的BeanDefinition,也可以修改BeanFactory的相关属性BeanFactoryPostProcessors它是Spring容器中很重要的一个接口,在Bean实例化之前执行
BeanFactoryPostProcessors有很多重要的实现类-
ConfigurationClassPostProcessor: 它内部实现了对@Configuration、@Bean、@Component、@ComponentScan、@Import、@ImportResource注解的解析逻辑 -
CustomEditorConfigurer:注册用户自定义的属性编辑器。参考上篇笔记: 第8节 Spring源码之 prepareBeanFactory 方法 -
PropertyResourceConfigurer: -
CustomAutowireConfigurer:
-
2. BeanDefinitionRegistryPostProcessor
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor子接口,是对BeanFactoryPostProcessor的扩展,它可以在常规的BeanFactoryPostProcessor执行之前注册更多的BeanDefinitionBeanDefinitionRegistryPostProcessor的实现类可以同时实现postProcessBeanFactory和postProcessBeanDefinitionRegistry方法
3. 如何使用BeanFactoryPostProcessors和 BeanDefinitionRegistryPostProcessor
在介绍 BeanFactoryPostProcessors和 BeanDefinitionRegistryPostProcessor 的使用之前。再次说明一下 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()) 方法流程,从大的方面来看,可以分为两个步骤:
(1)首先执行 入参 beanFactoryPostProcessors 和容器中的所有 BeanDefinitionRegistryPostProcessor,执行 BeanDefinitionRegistryPostProcessor的流程图如下
(2)再次执行 BeanFactoryPostProcessors,执行 BeanFactoryPostProcessors 的流程和执行 BeanDefinitionRegistryPostProcessor基本相似
BeanFactoryPostProcessors的基本使用
public class UserBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition user = beanFactory.getBeanDefinition("user");
System.out.println("测试 UserBeanFactoryPostProcessor , beanClassName : " + user.getBeanClassName());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="user" class="com.sff.demo.bean.User">
<property name="username" value="Tom"></property>
</bean>
<bean id="userBeanFactoryPostProcessor" class="com.sff.demo.bean.UserBeanFactoryPostProcessor"></bean>
</beans>
- 在
BeanDefinitionRegistryPostProcessor执行过程中添加其他的BeanDefinitionRegistryPostProcessor
public class NewBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {
private String processor;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println(" **** 执行了:NewBeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 方法 **** ");
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println(" **** 执行了:NewBeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法 **** ");
}
@Override
public int getOrder() {
return 0;
}
public String getProcessor() {
return processor;
}
public void setProcessor(String processor) {
this.processor = processor;
}
@Override
public String toString() {
return "NewBeanDefinitionRegistryPostProcessor { " +
"processor = '" + processor + ''' +
'}';
}
}
在执行 AddBeanDefinitionRegistryPostProcessor 的过程中新注册 NewBeanDefinitionRegistryPostProcessor
public class AddBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("《《《《执行了:AddBeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 方法》》》》");
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("《《《《执行了:AddBeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法,并新增一个 BeanDefinitionRegistryPostProcessor 》》》》");
BeanDefinitionBuilder newDef = BeanDefinitionBuilder.rootBeanDefinition(NewBeanDefinitionRegistryPostProcessor.class);
newDef.addPropertyValue("processor", "NewBeanDefinitionRegistryPostProcessor");
registry.registerBeanDefinition("newBeanDef", newDef.getBeanDefinition());
}
@Override
public int getOrder() {
return 0;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="userBeanFactoryPostProcessor" class="com.sff.demo.processor.AddBeanDefinitionRegistryPostProcessor"></bean>
</beans>
public class TestBean {
public static void main(String[] args) {
testBeanPostProcessor();
}
public static void testBeanPostProcessor() {
ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext("application-bfpp.xml");
System.out.println("testBeanPostProcessor 运行结果 : " + cx.getBean("newBeanDef"));
}
}
运行结果:
通过这个示例我们就可以明白 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()) 方法中每执行一段逻辑后都要重新执行代码块:
postProcessorNames = beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class,true, false);
的原因了,就是因为可以动态的在 BeanDefinitionRegistryPostProcessor 执行过程中添加其他的BeanDefinitionRegistryPostProcessor导致的。