BeanFactory的后置处理器就是BeanFactoryPostProcessor接口,该接口有一个方法postProcessBeanFactory,这个方法会在BeanFactory初始化之后调用,这时所有的bean定义(BeanDefinition)已经保存加载到beanFactory,但是bean的实例还未创建,可以通过BeanFactory对BeanDefinition的内容进行修改,也可以增加BeanDefinition。
BeanFactoryPostProcessor
先自定义一个BeanFactoryPostProcessor:
package com.morris.spring.demo.ext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import java.util.Arrays;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanPostProcessor.postProcessBeanFactory");
Arrays.asList(beanFactory.getBeanDefinitionNames()).forEach(System.out::println);
}
}
将自定义的BeanFactoryPostProcessor注入到容器中:
new AnnotationConfigApplicationContext(MyBeanFactoryPostProcessor.class);
也可以通过applicationContext.addBeanFactoryPostProcessor()
将自定义的BeanFactoryPostProcessor注入到容器中:
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
applicationContext.refresh();
当然也可以像容器中注入任意bean的方式注入,如在类上加个@Compoent,让容器扫描到;在配置类中使用@Bean注入。
运行结果如下:
MyBeanPostProcessor.postProcessBeanFactory
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口,它有一个postProcessBeanDefinitionRegistry方法,这个方法会在父接口BeanFactoryPostProcessor的postProcessBeanFactory()方法之前执行,可以用来给容器中添加新的BeanDefinition,后续容器会根据BeanDefinition注入对应的Bean。
自定义BeanDefinitionRegistryPostProcessor:
package com.morris.spring.demo.ext;
import com.morris.spring.entity.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import java.util.Arrays;
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry");
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
PropertyValue username = new PropertyValue("username", "morris");
beanDefinition.getPropertyValues().addPropertyValue(username);
PropertyValue age = new PropertyValue("age", 18);
beanDefinition.getPropertyValues().addPropertyValue(age);
registry.registerBeanDefinition("user", beanDefinition);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor.postProcessBeanFactory");
Arrays.asList(beanFactory.getBeanDefinitionNames()).forEach(System.out::println);
}
}
自定义的BeanDefinitionRegistryPostProcessor同样可以使用register和addBeanFactoryPostProcessor注入,这两种注入方法在执行顺序上会有点不一样,使用addBeanFactoryPostProcessor
注入的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry会先执行,这一点后面可以在源码分析中看到。
运行结果如下:
MyBeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry
MyBeanDefinitionRegistryPostProcessor.postProcessBeanFactory
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myBeanDefinitionRegistryPostProcessor
user
User(username=morris, age=18)
BeanFactoryPostProcessor的执行原理分析
BeanFactoryPostProcessor的执行逻辑是在PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors中:
// BeanFactoryPostProcessor有两类
// 一类就是BeanFactoryPostProcessor,方法postProcessBeanFactory,方法会在所有的BeanDefinition加载完成后执行
// 一类是BeanFactoryPostProcessor的子接口BeanDefinitionRegistryPostProcessor,方法postProcessBeanDefinitionRegistry,可以使用此方法往容器中注入BeanDefinition,也可以修改容器中的BeanDefinition
// postProcessBeanDefinitionRegistry方法在postProcessBeanFactory之前执行
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 这里的beanFactoryPostProcessors是通过beanFactory.addBeanFactoryPostProcessor注入的
// 先调用自己注入的BeanDefinitionRegistryPostProcessor的
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 调用BeanDefinitionRegistryPostProcessor.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.
// 实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
// 这里默认会有一个org.springframework.context.annotation.internalConfigurationAnnotationProcessor=ConfigurationClassPostProcessor
/**
* AnnotationConfigApplicationContext构造方法中
* this.reader = new AnnotatedBeanDefinitionReader(this);
* 这个类何时被注入?AnnotatedBeanDefinitionReader中注入
* @see org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors
*/
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// beanFactory.getBean会完成BeanFactoryPostProcessord
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 调用BeanDefinitionRegistryPostProcessor.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.addAll(currentRegistryProcessors);
// 调用BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
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);
// 调用BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// BeanFactoryPostProcessor的postProcessBeanFactory
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
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!
// 获取spring容器所有实现了BeanFactoryPostProcessor接口的beandefinitin
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 默认情况下priorityOrderedPostProcessors为空
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); // 实现了PriorityOrdered的BeanFactoryPostProcessor集合
List<String> orderedPostProcessorNames = new ArrayList<>(); // 实现了Ordered的BeanFactoryPostProcessor beanname集合
List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 未实现PriorityOrdered和Ordered的BeanFactoryPostProcessor beanname集合
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排序
// 根据PriorityOrdered接口的getOrder方法进行排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 调用实现了PriorityOrdered接口的BeanFactoryPostProcessor的postProcessBeanFactory
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 默认情况下,实现了Ordered接口的BeanFactoryPostProcessors为空
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); // 实现了Ordered的BeanFactoryPostProcessor集合
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// 对实现了Ordered接口的BeanFactoryPostProcessors排序
// 根据Ordered接口的getOrder方法进行排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 调用实现了Ordered接口的BeanFactoryPostProcessor的postProcessBeanFactory
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
// nonOrderedPostProcessors有一个org.springframework.context.event.internalEventListenerProcessor=EventListenerMethodProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); // 未实现PriorityOrdered和Ordered的BeanFactoryPostProcessor集合
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// 调用未实现PriorityOrdered和Ordered的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();
}