BeanDefinitionRegistryPostProcessor是BeanDefinition注册到容器的后置处理,他继承了bean工厂的后置处理器BeanFactoryPostProcessor,在执行顺序上它要比BeanFactoryPostProcessor先执行。此时bean还没有初始化。
自定义一个BeanDefinitionRegistryPostProcessor,在bean定义注册完以后,手动注册一个实例进去,代码如下:
@Component
@Slf4j
public class DemoBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
log.info("当前注册到容器中的bean的数量为:{}", registry.getBeanDefinitionCount());
registry.registerBeanDefinition("demoEntity", new RootBeanDefinition(DemoEntity.class));
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
log.info("当前容器中bean的数量为:{}", beanFactory.getBeanDefinitionCount());
log.info(JSON.toJSONString(beanFactory.getBeanDefinition("demoEntity")));
}
}
打印结果为:
2020-01-14 17:15:57.915 INFO 19808 — [ main] .DemoBeanDefinitionRegistryPostProcessor : 当前注册到容器中的bean的数量为:129
2020-01-14 17:15:57.960 INFO 19808 — [ main] .DemoBeanDefinitionRegistryPostProcessor : 当前容器中bean的数量为:130
2020-01-14 17:15:58.024 INFO 19808 — [ main] .DemoBeanDefinitionRegistryPostProcessor : {“abstract”:false,“autowireCandidate”:true,“autowireMode”:0,“beanClass”:“com.example.demo.entity.DemoEntity”,“beanClassName”:“com.example.demo.entity.DemoEntity”,“constructorArgumentValues”:{“argumentCount”:0,“empty”:true,“genericArgumentValues”:[],“indexedArgumentValues”:{}},“dependencyCheck”:0,“enforceDestroyMethod”:true,“enforceInitMethod”:true,“lenientConstructorResolution”:true,“methodOverrides”:{“empty”:true,“overrides”:[]},“nonPublicAccessAllowed”:true,“primary”:false,“propertyValues”:{“converted”:false,“empty”:true,“propertyValueList”:[],“propertyValues”:[]},“prototype”:false,“qualifiers”:[],“resolvableType”:{“array”:false,“componentType”:{“array”:false,“componentType”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"@"}̲,"generics":[],…EmptyType@1d3e6d34”},“superType”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"@"}̲,"type":{"ref”:“KaTeX parse error: Expected 'EOF', got '}' at position 38: …entType.source"}̲},"generics":[]…ref”:“KaTeX parse error: Expected 'EOF', got '}' at position 31: ….componentType"}̲,"generics":[],…ref”:"$.resolvableType.componentType"},“type”:“java.lang.Object”},“type”:“com.example.demo.entity.DemoEntity”},“resolvedAutowireMode”:0,“role”:0,“scope”:"",“singleton”:true,“synthetic”:false}
org.springframework.context.support.AbstractApplicationContext#refresh
>org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors
>org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 这里存储处理过的bean的名称,避免重复处理
Set processedBeans = new HashSet<>();
// AnnotationConfigServletWebServerApplicationContext继承了BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// BeanFactoryPostProcessor 需要调用postProcessBeanFactory
List regularPostProcessors = new ArrayList<>();
// BeanDefinitionRegistryPostProcessor既需要执行postProcessBeanFactory,还需要先执行postProcessBeanDefinitionRegistry
// 这里的postProcessBeanDefinitionRegistry既包括框架硬编码写入的,也包括用户注册的
List registryProcessors = new ArrayList<>();
// 这里调用系统硬编码写入的registryProcessor的postProcessBeanDefinitionRegistry方法
// registryProcessor和regularPostProcessors的postProcessBeanFactory放在后面统一处理
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 把注册到容器中的BeanDefinitionRegistryPostProcessor取出来,按照PriorityOrdered、Ordered和其他的顺序来执行
// 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.
// 创建临时列表,列表内的对象按照Order值从小到大的顺序来执行
List currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
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.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement 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);
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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 用户注册到容器中的BeanFactoryPostProcessor(不包括BeanDefinitionRegistryPostProcessors)还没有调用
// 这里同样以PriorityOrdered、Ordered、其他的顺序在临时队列里面排序然后执行
// 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 priorityOrderedPostProcessors = new ArrayList<>();
// 同样的,这里因为前面执行的处理器可以修改后面的处理器,所以这里只保存beanName
List orderedPostProcessorNames = new ArrayList<>();
List 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.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List 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.
List 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...
beanFactory.clearMetadataCache();
}