系列文章目录
文章目录
- 系列文章目录
- 前言
- 代码块一:invokeBeanFactoryPostProcessors
- 代码块二:getBeanFactoryPostProcessors
- 代码块三:invokeBeanFactoryPostProcessors
- 代码块四:sortPostProcessors
- 基本使用
- 总结
前言
已经介绍了obtainFreshBeanFactory方法,下面我们进入下一个比较重要的方法invokeBeanFactoryPostProcessors。
BeanFactoryPostProcessor接口是Spring初始化BeanFactory时对外暴露的扩展点, SpringIoc容器允许BeanFactoryPostProcessor在实例化Bean之前对bean定义进行修改。 BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor一个子接口,它具有更高的优先级,先于BeanFactoryPostProcessor执行,主要用来在BeanFactoryPostProcessor执行之前胡策一些其他的bean定义。比如:在BeanDefinitionRegistryPostProcessor注册一个BeanFactoryPostProcessor,因为此时BeanFactoryPostProcessor还未开始执行。
代码块一:invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
1、getBeanFactoryPostProcessors获取已经注册的BeanFactoryPostProcessor
2、invokeBeanFactoryPostProcessors实例化调用已经注册的BeanFactoryPostProcessor后置处理
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()));
}
}
1、getBeanFactoryPostProcessors获取已经注册的BeanFactoryPostProcessor见代码块二
2、invokeBeanFactoryPostProcessors实例化调用已经注册的BeanFactoryPostProcessor后置处理见代码块三
代码块二:getBeanFactoryPostProcessors
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
这儿默认情况下是null,但是我们可以添加,在前置刷新:代码块十一中介绍了该方法是一个对Spring的扩展,我们在web.xml中可以配置添加。
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>zgf.library.utils.SpringApplicationInit</param-value>
</context-param>
这儿继承ApplicationContextInitializer实现initialize方法将自定义的bean添加到应用上下文当中。
public class SpringApplicationInit implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(ConfigurableApplicationContext applicationContext) {
MyBeanInit myBeanInit = new MyBeanInit();
applicationContext.addBeanFactoryPostProcessor(myBeanInit);
}
}
代码块三:invokeBeanFactoryPostProcessors
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
1、记录已经执行后置处理的bean定义
Set<String> processedBeans = new HashSet<String>();
2、判断当前bean定义是否实现了BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
2.1、存放实现BeanFactoryPostProcessor的bean定义
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
2.2、存放实现BeanDefinitionRegistryPostProcessor的bean定义
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
2.3如果入参的beanFactoryPostProcessors实现了BeanDefinitionRegistryPostProcessor则直接后置处理
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
2.4添加到已经执行的缓存中
registryPostProcessors.add(registryPostProcessor);
}
else {
2.5添加到普通的缓存中
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.
3、获取所有实现BeanDefinitionRegistryPostProcessor的bean定义
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
3.1、记录实现了PriorityOrdered接口的bean
List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
3.2、校验是否实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
3.3、创建该后置处理的实例
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
3.4添加到已经执行的缓存中,避免重复执行
processedBeans.add(ppName);
}
}
3.4、排序
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
3.5、添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryPostProcessors.addAll(priorityOrderedPostProcessors);
3.6、BeanDefinitionRegistryPostProcessor的后置处理
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
4.1、找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor,
可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找,
下面的步骤和处理PriorityOrdered一样不做介绍
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
registryPostProcessors.addAll(orderedPostProcessors);
4.2、BeanDefinitionRegistryPostProcessor的后置处理
invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
5、最后处理剩下的实现BeanDefinitionRegistryPostProcessor接口的bean(就是既没有实现Ordered,也没有实现PriorityOrdered的)
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
registryPostProcessors.add(pp);
processedBeans.add(ppName);
5.1、BeanDefinitionRegistryPostProcessor的后置处理
pp.postProcessBeanDefinitionRegistry(registry);
reiterate = true;
}
}
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
6.1、这儿是执行实现了BeanDefinitionRegistryPostProcessor并且执行完毕,然后开始执行BeanFactoryPostProcessor的后置处理
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
6.2、这儿执行的是只实现了BeanFactoryPostProcessor的后置处理
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
7、对应2 直接执行BeanFactoryPostProcessor的后置处理
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!
8、获取所有的实现了BeanFactoryPostProcessor的bean定义
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
9.1、记录实现了PriorityOrdered接口的bean
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
9.2、记录实现Ordered接口的bean
List<String> orderedPostProcessorNames = new ArrayList<String>();
9.3、既没有实现Ordered和PriorityOrdered的bean
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
9.4、当前bean已经处理过了,直接跳过
// skip - already processed in first phase above
}
9.6、添加继承不同排序接口的bean到对应的容器当中
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(beanFactory, priorityOrderedPostProcessors);
9.7、先执行实现了PriorityOrdered接口
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(beanFactory, orderedPostProcessors);
9.8、在执行实现了Ordered接口的
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
9.9、最后执行未实现任何接口的bean
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();
}
这儿比较重要的是后置处理器的执行顺序,稍后会做讲解。
3.4 排序见代码块四
代码块四:sortPostProcessors
private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
Comparator<Object> comparatorToUse = null;
if (beanFactory instanceof DefaultListableBeanFactory) {
// 1.获取设置的比较器
comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
}
if (comparatorToUse == null) {
// 2.如果没有设置比较器, 则使用默认的OrderComparator
comparatorToUse = OrderComparator.INSTANCE;
}
// 3.使用比较器对postProcessors进行排序
Collections.sort(postProcessors, comparatorToUse);
}
默认情况下,比较器为 OrderComparator;如果配置了 annotation-config,并且值为true,使用的是 AnnotationAwareOrderComparator( Spring IoC:context:component-scan节点解析 代码块十五中设置了dependencyComparator 属性为 AnnotationAwareOrderComparator.INSTANCE),AnnotationAwareOrderComparator 继承自 OrderComparator,只是重写了部分方法,比较器的部分代码如下:
@Override
public int compare(Object o1, Object o2) {
return doCompare(o1, o2, null);
}
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;
}
基本使用
BeanDefinitionRegistryPostProcessor基本使用
package com.joonwhee.open.demo.spring;
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 MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry");
// 自己的逻辑处理
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor#postProcessBeanFactory");
// 自己的逻辑处理
}
@Override
public int getOrder() {
return 0;
}
}
BeanFactoryPostProcessor 的基本使用
package com.joonwhee.open.demo.spring;
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 MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor#postProcessBeanFactory");
// 自己的逻辑处理
}
}
总结
1、整个invokeBeanFactoryPostProcessors主要围绕两个接口来进行展开,一个是BeanDefinitionRegistryPostProcessor,另一个是BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的实现,BeanDefinitionRegistryPostProcessor拥有更高的优先级。
2、该方法一共操作了三种参数对象
- 入参的beanFactoryPostProcessors,这个是由Spring系列源码学习笔记:代码块十一自定义添加进来的。
- BeanDefinitionRegistryPostProcessor接口的实现类
- BeanFactoryPostProcessor接口的实现类
3、 执行顺序
1、入参的beanFactoryPostProcessors,并且继承了BeanDefinitionRegistryPostProcessor的后置处理 2.3
2、入参BeanDefinitionRegistryPostProcessor接口的实现类,并且继承了PriorityOrdered接口 3.6
3、入参BeanDefinitionRegistryPostProcessor接口的实现类,并且继承了Ordered接口4.2
4、入参BeanDefinitionRegistryPostProcessor接口的实现类,未实现任何排序接口(除了2,3剩余的实现) 5.1
5、入参BeanDefinitionRegistryPostProcessor接口的实现类,BeanFactoryPostProcessor的后置处理 6.1
6、入参BeanFactoryPostProcessor的接口实现类,BeanFactoryPostProcessor的后置处理 6.2
到这儿入参的后置处理解析完毕
7、BeanFactoryPostProcessor接口的实现类,并且继承了PriorityOrdered接口 9.1
8、BeanFactoryPostProcessor接口的实现类,并且继承了Ordered接口 9.2
9、BeanFactoryPostProcessor接口的实现类,未实现任何排序接口 9.3
4.本文还引入了两个用于排序的重要接口:PriorityOrdered 和 Ordered,其中 PriorityOrdered 继承了 Ordered,并且 PriorityOrdered 的优先级要高于 Ordered,这跟 BeanDefinitionRegistryPostProcessor 继承 BeanFactoryPostProcessor 有点类似。实现 Ordered 接口需要重写 getOrder 方法,返回一个用于排序的 order 值,order 值的范围为 Integer.MIN_VALUE ~ Integer.MAX_VALUE,order 值越小优先级越高,Integer.MIN_VALUE 拥有最高优先级,而 Integer.MAX_VALUE 则对应的拥有最低优先级。