背景
該文章中的Spring版本為5.2.12.RELEASE,對(duì)于不同的版本可能在某些實(shí)現(xiàn)上略有不同蒸矛。不過(guò)不會(huì)影響整體學(xué)習(xí)。
在之前的講BeanPostProcessor中講過(guò)它可以對(duì)Spring Bean實(shí)例做擴(kuò)展庶弃,而今天要說(shuō)的BeanFactoryPostProcessor與BeanPostProcessor類似,從它名字也可以知道它主要是對(duì)BeanFactory做擴(kuò)展马僻。我們可以通過(guò)BeanFactoryPostProcessor對(duì)Spring Bean的元信息(即BeanDefinition)進(jìn)行讀取和修改肢娘,它的作用點(diǎn)是在Spring Bean實(shí)例化之前墓阀。
接口定義
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* 在BeanFactory標(biāo)準(zhǔn)初始化之后荡灾,修改應(yīng)用程序上下文的內(nèi)部BeanFactory瓤狐。所有bean定義都將被加載,但尚未實(shí)例化任何bean批幌。這甚至可以覆蓋或添加屬性础锐,甚至可以用于初始化bean
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
有一點(diǎn)在代碼注釋中強(qiáng)調(diào)過(guò),BeanFactoryPostProcessor可以與Bean定義進(jìn)行交互并進(jìn)行修改荧缘,但不能與Bean實(shí)例進(jìn)行交互皆警。這樣做可能會(huì)導(dǎo)致bean實(shí)例化過(guò)早,從而違反了容器并造成了意外的副作用胜宇。如果需要bean實(shí)例交互耀怜,請(qǐng)考慮改為實(shí)現(xiàn)BeanPostProcessor恢着。
使用
代碼如下:
public class App1 {
public static void main(String[] args) {
//創(chuàng)建ClassPathXmlApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-bean-factory-post-processor.xml");
//獲取并打印出user Bean
User user = context.getBean(User.class);
System.out.println(user);
//獲取user BeanDefinition
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
BeanDefinition userBeanDefinition = beanFactory.getBeanDefinition("user");
//打印出user BeanDefinition中的值
for (PropertyValue propertyValue : userBeanDefinition.getPropertyValues()) {
String name = propertyValue.getName();
if (propertyValue.getValue() instanceof TypedStringValue){
TypedStringValue temp = (TypedStringValue) propertyValue.getValue();
System.out.printf("App1-修改之后:name = %s, value = %s\r\n",name,temp.getValue());
}
}
}
}
class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition("user");
for (PropertyValue propertyValue : beanDefinition.getPropertyValues()) {
String name = propertyValue.getName();
if (propertyValue.getValue() instanceof TypedStringValue){
TypedStringValue temp = (TypedStringValue) propertyValue.getValue();
System.out.printf("MyBeanFactoryPostProcessor-修改之前:name = %s, value = %s\r\n",name,temp.getValue());
Optional.ofNullable(temp.getValue()).ifPresent(value -> temp.setValue(value.toUpperCase()));
}
}
}
}
class User{
private String userName;
public User() {
System.out.println("User構(gòu)造方法被調(diào)用");
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
'}';
}
}
spring-bean-factory-post-processor.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.buydeem.factprybeanpostprocessor.User">
<property name="userName" value="tom"/>
</bean>
<bean class="com.buydeem.factprybeanpostprocessor.MyBeanFactoryPostProcessor"/>
</beans>
上面的代碼中定義了一個(gè)MyBeanFactoryPostProcessor桐愉,它的主要作用就是將User中的userName值轉(zhuǎn)為大寫(xiě)。最后打印結(jié)果如下:
MyBeanFactoryPostProcessor-修改之前:name = userName, value = tom
User構(gòu)造方法被調(diào)用
User{userName='TOM'}
App1-修改之后:name = userName, value = TOM
下面我們分析打印結(jié)果:
MyBeanFactoryPostProcessor-修改之前:name = userName, value = tom
該結(jié)果是在postProcessBeanFactory方法中打印出來(lái)的掰派。在我們的實(shí)現(xiàn)中从诲,我們獲取到在XML配置中定義的BeanDefinition信息,然后將userName的屬性值修改為大寫(xiě)靡羡。
User構(gòu)造方法被調(diào)用
User{userName='TOM'}
App1-修改之后:name = userName, value = TOM
該結(jié)果說(shuō)明postProcessBeanFactory方法確實(shí)是在Spring Bean實(shí)例化之前系洛,而我們修改了BeanDefinition導(dǎo)致創(chuàng)建的User實(shí)例的值為修改后的值俊性,且我們修改的是BeanDefinition,將tom改成TOM描扯。
BeanDefinitionRegistryPostProcessor
定義
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* 在容器初始化完成之后定页,可以修改BeanDefinition列表。
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
從定義中可以看出绽诚,BeanDefinitionRegistryPostProcessor為BeanFactoryPostProcessor的子接口典徊,該接口提供的postProcessBeanDefinitionRegistry可以在容器初始化完成之后修改BeanDefinition列表。簡(jiǎn)單的說(shuō)就是我們可以通過(guò)該接口增加或者刪除容器中BeanDefinition的定義恩够。
如何使用
代碼如下:
public class App2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean-factory-post-processor.xml");
//獲取并打印User
User user = context.getBean(User.class);
System.out.println(user);
}
}
class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class)
.addPropertyValue("userName", "tom")
.getBeanDefinition();
registry.registerBeanDefinition("user",beanDefinition);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
class User{
private String userName;
public User() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
'}';
}
}
bean-factory-post-processor.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.buydeem.spring.beanfactorypostprocessor.MyBeanDefinitionRegistryPostProcessor"/>
</beans>
在配置文件中我們只定義了MyBeanDefinitionRegistryPostProcessor卒落,并沒(méi)有定義User實(shí)例。但是我們還是能從容器中獲取到User實(shí)例蜂桶。這個(gè)實(shí)例就是我們?cè)贛yBeanDefinitionRegistryPostProcessor中的postProcessBeanDefinitionRegistry方法中添加的儡毕,最后容器成功的幫我們把User實(shí)例創(chuàng)建出來(lái)。
如何注冊(cè)BeanFactoryPostProcessor
在我們之前的示例中我們只是在配置文件中定義了BeanFactoryPostProcessor扑媚,它是如何并注冊(cè)到ApplicationContext中的呢腰湾?在定義的文檔中有說(shuō)明,總體來(lái)說(shuō)有兩種方式:在配置文件中定義疆股,然后會(huì)并自動(dòng)注冊(cè)到容器中來(lái)檐盟;另一種就是通過(guò)API添加到容器中,通過(guò)ConfigurableApplicationContext提供的方法押桃,我們可以手動(dòng)將BeanFactoryPostProcessor注冊(cè)到容器中葵萎。
對(duì)于上面兩種方式,我們都可以通過(guò)AbstractApplicationContext中的源碼來(lái)了解唱凯。
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
這個(gè)是ConfigurableApplicationContext接口的實(shí)現(xiàn)羡忘,代碼很簡(jiǎn)單,就是通過(guò)一個(gè)beanFactoryPostProcessors列表來(lái)保存BeanFactoryPostProcessor磕昼。另外一種就是在配置文件中定義卷雕,然后自動(dòng)應(yīng)用。
從AbstractApplicationContext的refresh開(kāi)始看票从,然后調(diào)用invokeBeanFactoryPostProcessors方法漫雕。這個(gè)方法的內(nèi)容很簡(jiǎn)單,主要就是調(diào)用PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())峰鄙,下面我們分析該方法就能了解它是如何實(shí)現(xiàn)的了浸间。
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// 存儲(chǔ)已經(jīng)執(zhí)行完成的BeanFactoryPostProcessor
Set<String> processedBeans = new HashSet<>();
//判斷beanFactory是不是BeanDefinitionRegistry,只有是該類型才能執(zhí)行BeanDefinitionRegistryPostProcessor
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//存儲(chǔ)BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//存儲(chǔ)BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//迭代處理已經(jīng)在AbstractApplicationContext中的beanFactoryPostProcessors
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//如果BeanDefinitionRegistryPostProcessor則要執(zhí)行postProcessBeanDefinitionRegistry方法吟榴,并將其添加到registryProcessors列表中
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
//如果是BeanFactoryPostProcessor則直接添加到regularPostProcessors列表中
else {
regularPostProcessors.add(postProcessor);
}
}
//用來(lái)臨時(shí)存儲(chǔ)BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
//執(zhí)行實(shí)現(xiàn)了PriorityOrdered的BeanDefinitionRegistryPostProcessor魁蒜。這個(gè)里面的是在配置文件中配置的BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//通過(guò)將其添加到臨時(shí)的currentRegistryProcessors和已執(zhí)行的processedBeans列表中
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//對(duì)BeanDefinitionRegistryPostProcessor排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加到registryProcessors中
registryProcessors.addAll(currentRegistryProcessors);
//執(zhí)行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空臨時(shí)列表
currentRegistryProcessors.clear();
//與上一步一致,只不過(guò)換做成實(shí)現(xiàn)了PriorityOrdered的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();
//循環(huán)處理剩下的BeanDefinitionRegistryPostProcessor知道沒(méi)有再出現(xiàn)
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();
}
//執(zhí)行所有的BeanFactoryPostProcessor,因?yàn)锽eanDefinitionRegistryPostProcessor也是BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
//因?yàn)閎eanFactory不是BeanDefinitionRegistry兜看,所以執(zhí)行所有的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//處理再配置文件中所定義的BeanFactoryPostProcessor锥咸,之前處理的是已經(jīng)添加到容器中的BeanFactoryPostProcessor和定義在配置文件中的BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
//將BeanFactoryPostProcessor按照不同類型(這里指的是是否有序)分組存儲(chǔ)
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);
}
}
//首先對(duì)實(shí)現(xiàn)了PriorityOrdered的進(jìn)行排序,然后執(zhí)行
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
//然后對(duì)實(shí)現(xiàn)了Ordered的進(jìn)行排序细移,然后執(zhí)行
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
//最后執(zhí)行剩下的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
beanFactory.clearMetadataCache();
}
代碼看起來(lái)比較復(fù)雜搏予,其實(shí)細(xì)看內(nèi)容并不是很復(fù)雜。它主要就是做兩件事弧轧,執(zhí)行BeanDefinitionRegistryPostProcessor和執(zhí)行BeanFactoryPostProcessor缔刹。從源碼也知道,BeanDefinitionRegistryPostProcessor中的postProcessBeanDefinitionRegistry方法是會(huì)早于BeanFactoryPostProcessor中的postProcessBeanFactory方法劣针;同時(shí)與BeanPostProcessor類似校镐,他們都是可以多個(gè)的,同時(shí)還可以定義順序捺典。
Spring源碼中的應(yīng)用
BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor在Spring框架中也有很多應(yīng)用鸟廓。
PropertySourcesPlaceholderConfigurer
該類作為BeanFactoryPostProcessor的子類,它可以用來(lái)處理配置中的${...}占位符信息襟己,它的使用示例如下:
public class App2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-bean-factory-post-processor-2.xml");
DbInfo dbInfo = context.getBean(DbInfo.class);
System.out.println(dbInfo);
}
}
@Data
@ToString
class DbInfo{
private String url;
private String userName;
}
spring-bean-factory-post-processor-2.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations" value="classpath*:jdbc.properties"/>
</bean>
<bean id="dbInfo" class="com.buydeem.factprybeanpostprocessor.DbInfo">
<property name="url" value="${jdbc.url}"/>
<property name="userName" value="${jdbc.userName}"/>
</bean>
</beans>
jdbc.properties配置文件如下:
jdbc.url=jdbcurl
jdbc.userName=tom
最后打印結(jié)果如下:
DbInfo(url=jdbcurl, userName=tom)
從結(jié)果我們可以知道引谜,在xml配置文件中的${jdbc.url}
和${jdbc.userName}
最終被jdbc.properties中的內(nèi)容替換,而它的實(shí)現(xiàn)則是通過(guò)BeanFactoryPostProcessor實(shí)現(xiàn)的擎浴。簡(jiǎn)單的說(shuō)就是我們?cè)趐ostProcessBeanFactory方法中將BeanDefinition中的占位符替換成properties文件中的對(duì)應(yīng)值即可员咽。
ConfigurationClassPostProcessor
在Spring中我們經(jīng)常使用@Configuration注解的、@Component贮预、@ComponentScan贝室、@Import、@ImportResource或者@Bean注解的用來(lái)標(biāo)記配置類仿吞,而ConfigurationClassPostProcessor作為BeanDefinitionRegistryPostProcessor的子類滑频,就是用來(lái)處理這些配置類,然后從其中解析出BeanDefinition信息注冊(cè)到容器中唤冈。
總結(jié)
對(duì)于BeanFactoryPostProcessor來(lái)說(shuō)峡迷,它針對(duì)BeanFactory做擴(kuò)展,即Spring會(huì)在BeanFactory初始化之后你虹,所有的BeanDefinition都已經(jīng)加載绘搞,但是Bean實(shí)例還未創(chuàng)建前調(diào)用,我們可以對(duì)BeanDefinition做修改傅物。
而B(niǎo)eanDefinitionRegistryPostProcessor的調(diào)用會(huì)在BeanFactoryPostProcessor之前夯辖,我們可以通過(guò)它在BeanFactoryPostProcessor之前注冊(cè)更多的BeanDefinition。