spring之BeanFactoryPostProcessor源码解析
BeanFactoryPostProcessor的介绍
前面三篇博客介绍了spring容器在初始化bean时所支持的几种自定义扩展方式,包含BeanPostProcessor、Aware、InitializingBean和init-method这几种扩展方式。这篇博客将会介绍BeanFactoryPostProcessor,BeanFactoryPostProcessor与前者的区别在于,它支持的扩展是在spring容器启动阶段做完标准初始化后(即BeanDefinition等初始化完成,但未完成真正的bean的初始化时),对BeanDefinition做出修改。即相当于在bean被初始化之前对BeanDefintion做出修改,从而达到改变bean的效果。
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
@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接口只定义了一个方法postProcessBeanFactory,入参为一个已经完成标准初始化的ConfigurableListableBeanFactory。
自定义BeanFactoryPostProcessor
定义一个普通bean
Doctor.java
package spring.ioc.pobean;
public class Doctor {
private String name;
private Integer age;
public Doctor (String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
自定义BeanFactoryPostProcessor
MyBeanFactoryPostProcessor.java
package spring.ioc;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
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 {
// 获取指定的 BeanDefinition
BeanDefinition bd = beanFactory.getBeanDefinition("doctor");
MutablePropertyValues pvs = bd.getPropertyValues();
pvs.addPropertyValue("age",28);
pvs.addPropertyValue("name","李四");
System.out.println("已修改BeanDefiniton" );
}
}
注解式配置类
MainConfigOfBeanFactoryPostProcessor.java
package spring.ioc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import spring.ioc.pobean.Doctor;
@ComponentScan("spring.ioc")
@Configuration
public class MainConfigOfBeanFactoryPostProcessor {
@Bean
public Doctor doctor(){
return new Doctor("张三", 18);
}
}
单元测试类
BeanFactoryPostProcessorTest.java
package spring.ioc.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import spring.ioc.MainConfigOfBeanFactoryPostProcessor;
import spring.ioc.pobean.Doctor;
public class BeanFactoryPostProcessorTest {
@Test
public void testBeanFactoryPostProcessor() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfBeanFactoryPostProcessor.class);
Doctor doctor = (Doctor) applicationContext.getBean("doctor");
System.out.println("从容器中获取的doctor.name="+doctor.getName() + "doctor.age=" + doctor.getAge());
}
}
运行结果分析
从结果可以看到,原本配置的Doctor是18岁的张三,现在通过自定义MyBeanFactoryPostProcessor对BeanDefinition进行修改后变成了28岁的李四。符合前面的理论介绍。
方法调用栈分析BeanFactoryPostProcessor的执行时机
从方法调用栈可以看出,BeanFactoryPostProcessor的执行时机是在前面博客经常介绍的AbstractApplictionContext的refresh方法中的invokeBeanFactoryPostProcessors步骤中,前面分析过BeanPostProcessor的执行时机也是在refresh这个方法的其中一个步骤中。这里再贴一下refresh源码
AbstractApplicationContext.java
@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.
//此步骤就是BeanFactoryPostProcessors的执行时机
invokeBeanFactoryPostProcessors(beanFactory);
// 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);
// 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();
}
}
}