作用:在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{@Overridepublic 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進行修改
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态