随笔分类
子类扩展 postProcessBeanFactory
BeanFactoryPostProcessor
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* 此处将 IOC容器本身传递了过来,只要属性容器本身,此时便可以去做一些额外的事:移除某些 beanDefinition,添加某些 beanDefinition,
* 或去修改覆盖某些 bean的属性值也是可以的
* 可以对容器中已经存在的 bd信息做任何相关的操作
* 这也是扩展点: 在容器创建(加载)任何 bean之前会去调用
* 例子:可以在创建 bean之前去修改 容器中的 bd信息 (比如:进行一些网络过滤等等)
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
调用 子类扩展的 beanFactoryPostProcessors
invokeBeanFactoryPostProcessors
这里会去调用子类扩展、注册的 beanFactoryPostProcessors
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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/**
* 对于 bdrpp,其需要去执行的后置处理器方法实则有两个:postProcessBeanDefinitionRegistry、postProcessBeanFactory
*/
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.
/** 存储已经执行过 beanFactoryPostProcessor的 beanName **/
Set<String> processedBeans = new HashSet<>();
/** CASE1: 条件成立, 说明当前 bf是 bd注册中心, bd全部都注册到 bf **/
if (beanFactory instanceof BeanDefinitionRegistry) {
// 将当前 bd转为 BeanDefinitionRegistry
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
/** 规整的、普通的 PostProcessors集合 **/
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
/** 存储 BeanDefinitionRegistryPostProcessors集合 **/
/** BeanDefinitionRegistryPostProcessors这种类型的容器后置处理器, 可以再向容器内手动硬编码来注册些 bd **/
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
/** 迭代处理 ApplicationContext上面硬编码注册的一些 BeanFactoryPostProcessors **/
/** 这里的处理器无非就两种类型:BeanFactoryPostProcessors、BeanDefinitionRegistryPostProcessors **/
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
/** 这里调用 可以向 bf再次注册一些 bd信息 **/
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到对应集合中去
registryProcessors.add(registryProcessor);
}
else {
// 添加到对应集合中去, 后续会统一执行一些方法
// 这里保存的就是 BeanFactoryPostProcessor类型的 bd
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.
/** 临时的, 当前阶段的 registry后处理器集合 **/
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
/** 使用 beanFactory获取 BeanDefinitionRegistryPostProcessor类型的全部 beanName **/
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
/** 迭代处理获取到的 beanName, 每个 beanName都是 BeanDefinitionRegistryPostProcessor类型的 **/
for (String ppName : postProcessorNames) {
/** 判断对应的 bean是否实现了 主排序接口 PriorityOrdered, 如果实现了, 就添加该 BeanDefinitionRegistryPostProcessors到 CurrentRegistryProcessors中去 **/
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 因为接下来就是要去执行 bdrpp的 registry相关接口方法, 因此需要将beanName添加到 processedBean中去, 表示已执行
processedBeans.add(ppName);
}
}
/** 对实现了 PriorityOrdered的类型为 bdrpp的后置处理器进行优先级排序, 根据 order值进行升序排序 **/
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到 registry类型后处理器集合中去
registryProcessors.addAll(currentRegistryProcessors);
/** 调用排序后的实现了主排序接口的 bdrpp对应的 postProcessBeanDefinitionRegistry(), 向 bf内注册 bd信息 **/
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
// 清空集合, 接下来还有用途
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
/** 这里实现的功能和上述十分相似, 区别在于这里处理的是实现了 Ordered接口的 bdrpp **/
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) /** 确保每个 bdrpp只会执行一次注册 bd的逻辑 **/ && beanFactory.isTypeMatch(ppName, Ordered.class)) {
/** 这也说明了为啥上面处理完 主排序接口后要进行 clear... **/
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
// 嗯, 这里又进行了 clear
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
/** 控制 while是否再次循环 **/
boolean reiterate = true;
/**
* 之所以使用循环方式, 是因为在循环中会找到 bdrpp并去执行对应的后置处理器方法来注册 bd,
* 此时注册的 bd有可能是 bdrpp类型的, 未避免遗漏, 因此需要使用变量 reiterate来控制循环
*/
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();
}
/** 来到这, 说明 bdrpp已经执行完了 postProcessBeanDefinitionRegistry方法 **/
/** 此时, bdrpp还有一种后置处理器需要去执行 postProcessBeanFactory方法 (因为其自身继承了 BeanFactoryPostProcessor) **/
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
/** 这里来执行 普通类型 (BeanFactoryPostProcessor) 的 后置处理器方法 **/
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
/** CASE2: 条件成立, 说明当前 bf不是 bd注册中心 **/
/** 这种情况, 我们忽略, 一般情况下 bf都是 BeanDefinitionRegistry类型的 **/
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
/** 上面的代码处理了 硬编码提供的 bdrpp、bfpp 这两种类型的后置处理器 **/
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
/** 获取容器内注册的 bfpp(这里区别于上述 "硬编码的") 类型的 beanName数组集合 **/
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
/** 主排序后处理器集合 --> 直接来存储 处理器本身 **/
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
/** 次排序后处理器集合 --> 存储的只是 name **/
List<String> orderedPostProcessorNames = new ArrayList<>();
/** 未实现排序接口的处理器集合 --> 存储的只是 name **/
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
/** 这里做的便是根据处理器类型添加到指定集合中去 **/
for (String ppName : postProcessorNames) {
/** 这里是为了避免重复执行, 因为 postProcessorNames中也会包含 bdrpp类型的 **/
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);
/** 根据 name来拿到指定的后处理器,再去执行 **/
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<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.
List<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...
beanFactory.clearMetadataCache();
}
BeanDefinitionRegistryPostProcessor
对于 bfrpp,其需要去执行的后置处理器方法实则有两个:postProcessBeanDefinitionRegistry、postProcessBeanFactory
/**
* 注意看, 这个类实际上是去实现了 BeanFactoryPostProcessor
*/
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* 如果有往容器中去新增 bd信息的需求, 最好是使用 postProcessBeanDefinitionRegistry方法
* 虽然使用 BeanFactoryPostProcessor中提供的 postProcessBeanFactory也能去实现同等功能, 但还是建议去使用 该方法
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
invokeBeanDefinitionRegistryPostProcessors
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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
注册后置处理器 registerBeanPostProcessors
registerBeanPostProcessors
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 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
/** 获取后处理器 beanName数组 --> 这里注册的是在 配置文件中注册的后置处理器集合, 并非 bf中硬编码注册的后置处理器 **/
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
/**
* 统计后置处理器的数量
* getBeanPostProcessorCount() 在 refresh中硬编码注册的处理器数量
* postProcessorNames.length 在配置中配置的后处理器的数量
*/
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
/** 检查创建 bean实例时, 后处理器框架是否已经全部注册完毕, 如果未完毕, 则进行打印日志的提示 **/
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
/** 存储实现了主排序接口后处理器集合 **/
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
/** 存储实现了 MergedBeanDefinitionPostProcessor接口的后处理器集合 **/
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
/** 存储实现了次排序接口的后处理器 name集合 **/
List<String> orderedPostProcessorNames = new ArrayList<>();
/** 存储未实现排序接口的后处理器 name集合 **/
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
/** 下面做的是根据后处理器优先级来做的事了 **/
/** 首先,遍历后处理器集合, 进行分类划分添加集合 **/
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
/** 下面干的事:排序及其注册后置处理器 **/
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory. getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
/** 排序内部处理器 **/
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
/** 重新添加, 确保 MergedBeanDefinitionPostProcessor类型的后处理器, 在后处理器 List的末尾 **/
registerBeanPostProcessors(beanFactory, internalPostProcessors);
/** 重新来添加后处理器监听器 **/
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
BeanPostProcessorChecker
public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
this.beanFactory = beanFactory;
this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
}
postProcessAfterInitialzation
# BeanPostProcessorChecker
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
// 条件1 -> true, 说明当前 bean是普通类型 bean, 不是后置处理器
// 条件2 -> true, 说明当前 bean是用户级别的 bean, 不是 Spring框架级别注入 的 bean实例
// 条件3 -> true, 说明 bf上硬编码注册的后处理器数量 < 后处理器总数, 说明当前 bean创建阶段时, 后处理器框架尚未初始化完毕... 需要打印日志提示
if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
if (logger.isInfoEnabled()) {
logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
"] is not eligible for getting processed by all BeanPostProcessors " +
"(for example: not eligible for auto-proxying)");
}
}
return bean;
}
registerBeanPostProcessors
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
if (beanFactory instanceof AbstractBeanFactory) {
// Bulk addition is more efficient against our CopyOnWriteArrayList there
((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
}
else {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
}
addBeanPostProcessors
/**
* 这里添加的后置处理器会在 bean的生命周期的各个阶段起作用
*/
public void addBeanPostProcessors(Collection<? extends BeanPostProcessor> beanPostProcessors) {
/** 这里就确保了不会重复添加后置处理器 **/
this.beanPostProcessors.removeAll(beanPostProcessors);
this.beanPostProcessors.addAll(beanPostProcessors);
}