作用:在Spring创建完BeanFactory之后(也可以说注册完BeanDefinition之后),会调用所有实现了BeanFactoryPostProcessor接口的实例的postProcessBeanFactory方法,目前的最大使用场景就是修改BeanDefinition
注册BeanDefinition请参考我的另一片文章BeanDefinitionRegistry
Spring.xml
<bean id="student" class="test.entity.Student" >
<property name="name" value="KAOMA" />
</bean>
<bean id="myBeanFactoryPostProcessor" class="test.config.MyBeanFactoryPostProcessor" />
实现类
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition bdf=beanFactory.getBeanDefinition("student");
MutablePropertyValues mpv=bdf.getPropertyValues();
TypedStringValue source=(TypedStringValue)mpv.get("name");
System.out.println("原来的name值是:"+source.getValue());
source.setValue("MASALAKA");
System.out.println("现在的name值是:"+source.getValue());
}
}
测试类
public static void main(String[] args) throws Exception {
ApplicationContext ac=new ClassPathXmlApplicationContext("spring-application.xml");
Student s=(Student)ac.getBean("student");
System.out.println("get bean"+s.getName());
}
当然,这个例子中,用BeanPostProcessor也可以做到的,因为此例子中是对Bean的值修改,而实际BeanFactoryPostProcessor接口目的是对BeanDefinition进行修改