Java bean,Spring-beans-BeanFactoryPostProcessor

 2023-10-15 阅读 27 评论 0

摘要:作用:在Spring創建完BeanFactory之后(也可以說注冊完BeanDefinition之后),會調用所有實現了BeanFactoryPostProcessor接口的實例的postProcessBeanFactory方法,目前的最大使用場景就是修改BeanDefinition 注冊BeanDefinition請參考我的另一

作用:在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進行修改

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/137110.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息