spring的组件工厂后置处理器——BeanFactoryPostProcessor
作用和调用时机
spring有两种后置处理器:
1. 组件后置处理器——org.springframework.beans.factory.config.BeanPostProcessor;
2. 工厂后置处理器——org.springframework.beans.factory.config.BeanFactoryPostProcessor。
根据名字可以看出,前者是处理组件的,后者是处理组件工厂的。
BeanPostProcessor的调用时机是在bean被实例化之后、初始化之前或之后的;
那么,BeanFactoryPostProcessor的调用时机是什么呢?先来截取一段sring源码。
@FunctionalInterface
public interface BeanFactoryPostProcessor { /**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException; }
从源码可以看出,BeanFactoryPostProcessor是一个接口,只有1个方法,用于修改springIOC容器内部的bean工厂,调用时机是容器标准初始化之后。什么是标准初始化?注释后面有解释:所有的bean定义都即将被加载,但是还没有bean被实例化。所以,BeanFactoryPostProcessor的方法肯定是在BeanPostProcessor的两个方法之前被调用的。
示例Demo
自定义BeanFactoryPostProcessor实现类
/**
* 自定义的BeanFactoryPostProcessor,即工厂后置处理器
* created on 2019-04-21
*/
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
/**
* 这个方法来自于BeanFactoryPostProcessor接口
* 用于修改关于容器的配置
* 调用时机:容器的标准初始化之后,这时所有的bean定义将要加载、但是并没有bean被实例化
* @param beanFactory
* @throws BeansException
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
int count = beanFactory.getBeanDefinitionCount();
String[] names = beanFactory.getBeanDefinitionNames();
System.out.println("MyBeanFactoryPostProcessor.postProcessBeanFactory正在执行");
System.out.println("共有" + count + "个组件,它们是:" + Arrays.asList(names));
}
}
普通bean类
/**
* bean类,通过实现接口的方式获取初始化和销毁时调用的方法
*/
@Component
public class Dog implements InitializingBean, DisposableBean { //属性
private String name;
private int age; //构造方法
public Dog() {
System.out.println("Dog:正在调用无参构造方法");
}
public Dog(String name, int age) {
System.out.println("正在调用带参构造方法");
this.name = name;
this.age = age;
} @Override
public void destroy() throws Exception {
System.out.println("Dog:正在调用销毁方法");
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("Dog:正在调用初始化方法");
} //getters & setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
容器配置类,自定义的工厂后置处理器必须在容器中注册才能生效
/**
* 容器配置类
* 注册自定义BeanFactoryPostProcessor
*/
@Configuration
@Import(value = {MyBeanFactoryPostProcessor.class})
public class BeanFactoryPostProcessorConfig { //注册普通bean类
@Bean
@Scope("singleton")
public Dog dog() {
return new Dog();
}
}
测试类
/**
* 用于测试自定义BeanFactoryPostProcessor
*/
public class BeanFactoryPostProcessorTest { @Test
public void test() {
//创建容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanFactoryPostProcessorConfig.class);
//关闭容器
applicationContext.registerShutdownHook();
}
}
测试结果
MyBeanFactoryPostProcessor.postProcessBeanFactory正在执行
共有9个组件,它们是:[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,
beanFactoryPostProcessorConfig, cn.monolog.processors.MyBeanFactoryPostProcessor,
cn.monolog.processors.MyBeanDefinitionRegistryPostProcessor,
dog]
Dog:正在调用无参构造方法
Dog:正在调用初始化方法
Dog:正在调用销毁方法
从测试结果可以看出:
BeanFactoryPostProcessor.postProcessBeanFactory方法被调用时,容器中确实已经有关于bean的定义,但是bean的实例化却是后来才执行的。
源码分析
我们从创建springIOC容器开始
org.springframework.context.annotation.AnnotationConfigApplicationContext
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given annotated classes and automatically refreshing the context.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
跟进refresh →
org.springframework.context.support.AbstractApplicationContext
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh(); // Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory); try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory); //1 // Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory); // Initialize message source for this context.
initMessageSource(); // Initialize event multicaster for this context.
initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses.
onRefresh(); // Check for listener beans and register them.
registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); //2 // Last step: publish corresponding event.
finishRefresh();
} catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
} // Destroy already created singletons to avoid dangling resources.
destroyBeans(); // Reset 'active' flag.
cancelRefresh(ex); // Propagate exception to caller.
throw ex;
} finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
在1处调用的是组件工厂后置处理器的方法,在2处才是bean实例化,继续跟进invokeBeanFactoryPostProcessors →
org.springframework.context.support.AbstractApplicationContext
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
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()));
}
}
首先调用了一个静态方法,后面是一堆关于类加载器的操作,跟进这个静态方法 →
org.springframework.context.support.PostProcessorRegistrationDelegate
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<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
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.
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.
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);
} // 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); //1 // 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)) {
// 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); //2 // 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); //3 // Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); //4 // Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
这个静态方法很长,前面有一段关于beanFactory instanceof BeanDefinitionRegistry的分支,会优先执行。这个分支是用来处理BeanDefinitionRegistryPostProcessor的,它是BeanFactoryPostProcessor的一个子接口,用于向容器中添加新的bean定义,调用时机在别的BeanFactoryPostProcessor之前。我们先不看它,直接看下面的普通BeanFactoryPostProcessor——
1处:从容器中根据类型获取所有的BeanFactoryPostProcessor的bean名称;
2处:首先执行实现了PriorityOrdered接口的BeanFactoryPostProcessor;
3处:然后执行实现了Ordered接口的BeanFactoryPostProcessor;
4处:最后执行其他的BeanFactoryPostProcessor,即没有实现任何排序接口的。
spring的组件工厂后置处理器——BeanFactoryPostProcessor的更多相关文章
- spring 后置处理器BeanFactoryPostProcessor和BeanPostProcessor的用法和区别
主要区别就是: BeanFactoryPostProcessor可以修改BEAN的配置信息而BeanPostProcessor不能,下面举个例子说明 BEAN类: package com.spring ...
- Spring容器中bean的生命周期以及关注spring bean对象的后置处理器:BeanPostProcessor(一个接口)
Spring IOC 容器对 Bean 的生命周期进行管理的过程: 1.通过构造器或工厂方法创建 Bean 实例 2.为 Bean 的属性设置值和对其他 Bean 的引用 3.将 Bean 实例传递给 ...
- Spring中Bean的后置处理器
以下内容引用自http://wiki.jikexueyuan.com/project/spring/bean-post-processors.html: Bean后置处理器 BeanPostProce ...
- 1.spring源码-BeanPostProcessor后置处理器
1.BeanPostProcessor接口的介绍: BeanPostProcessor是一个接口,其中有两个方法,postProcessBeforeInitialization和postProcess ...
- Spring的后置处理器BeanFactoryPostProcessor
新建一个JavaBean UserBeanFactoryPostProcessor 实现了BeanFactoryPostProcessor接口 Spring配置文件如下: 编写测试用例 从结果可以看出 ...
- Spring之BeanPostProcessor(后置处理器)介绍
为了弄清楚Spring框架,我们需要分别弄清楚相关核心接口的作用,本文来介绍下BeanPostProcessor接口 BeanPostProcessor 该接口我们也叫后置处理器,作用是在Be ...
- Spring点滴五:Spring中的后置处理器BeanPostProcessor讲解
BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...
- Spring Bean前置后置处理器的使用
Spirng中BeanPostProcessor和InstantiationAwareBeanPostProcessorAdapter两个接口都可以实现对bean前置后置处理的效果,那这次先讲解一下B ...
- spring学习四:Spring中的后置处理器BeanPostProcessor
BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...
随机推荐
- 【leetcode 136】136. Single Number
要求:给定一个整数数组,除了其中1个元素之外,其他元素都会出现两次.找出这个只出现1次的元素. 例: array =[3,3,2,2,1] 找出元素1. 思路:最开始的想法是用两次for循环,拿 ...
- 将shell脚本的执行过程和执行结果导入到log文件中
[root@localhost scripts]# vim ping.sh #!/bin/bash set -x ##分步执行 exec &> /tmp/log.txt ##脚本执行的过 ...
- 安装Python包报错——ReadTimeoutError
一.问题:安装python包的时候报错ReadTimeoutError——Read time out. 二.解决办法三种方法,一是切换下载源:二是下载相应平台的安装包后安装:三是下载源码编译安装: ...
- C++ ->error LNK1123
终极解决方案:VS2010在经历一些更新后,建立Win32 Console Project时会出“error LNK1123” 错误,解决方案为将 项目|项目属性|配置属性|清单工具|输入和输出|嵌入 ...
- 应急响应中find命令总结
在应急响应中,我们经常会使用find命令来查找系统中被黑客修改过的文件,或者被上传的木马后门文件,灵活使用find命令可以达到事半功倍的效果,现总结下使用技巧 举例,查找最近被更改的jsp文件 fin ...
- C++ 6小时刷完面向对象
**本篇博文参考视频见我上一篇博文的第一行**### 类和对象的声明- 类的声明```class People{ int a; void fun(){ cout<<"fun&qu ...
- ROPE
#include <ext/rope> using namespace __gnu_cxx; ]; rope<int> x; rope<int> x(a,a + n ...
- zabbix服务的布置(脚本)
一,服务端配置 #!/bin/bash#clsn #设置解析 注意:网络条件较好时,可以不用自建yum源# echo '10.0.0.1 mirrors.aliyuncs.com mirrors.al ...
- web性能优化--算法优化(四)
避免for-in 把数组长度保存在局部变量中 较少迭代次数(Duffs Device) 基于函数的循环比基于循环的迭代消耗性能更多 优化if-else,一般switch比if-else速度快(hash ...
- 集合综合练习<一>
1208421001,关羽,数学,93 1208421001,关羽,英语,88 1208421002,张飞,语文,82 1208421002,张飞,数学,83 1208421002,张飞,英语,89 ...