Spring容器扩展点:后置处理器BeanFactoryPostProcessor

- 日理万妓 2022-05-17 09:15 281阅读 0赞

BeanPostProcessor(Bean后置处理器)常用在对bean内部的值进行修改;实现Bean的动态代理等。
BeanFactoryPostProcessor和BeanPostProcessor都是spring初始化bean时对外暴露的扩展点。但它们有什么区别呢?
由《理解Bean生命周期》的图可知:BeanFactoryPostProcessor是生命周期中最早被调用的,远远早于BeanPostProcessor。它在spring容器加载了bean的定义文件之后,在bean实例化之前执行的。也就是说,Spring允许BeanFactoryPostProcessor在容器创建bean之前读取bean配置元数据,并可进行修改。例如增加bean的属性和值,重新设置bean是否作为自动装配的侯选者,重设bean的依赖项等等。

在srping配置文件中可以同时配置多个BeanFactoryPostProcessor,并通过在xml中注册时设置’order’属性来控制各个BeanFactoryPostProcessor的执行次序。

BeanFactoryPostProcessor接口定义如下:

  1. public interface BeanFactoryPostProcessor {
  2. void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
  3. }

接口只有一个方法postProcessBeanFactory。该方法的参数是ConfigurableListableBeanFactory类型,实际开发中,我们常使用它的getBeanDefinition()方法获取某个bean的元数据定义:BeanDefinition。它有这些方法:
这里写图片描述

看个例子:
配置文件中定义了一个bean:

  1. <bean id="messi" class="twm.spring.LifecycleTest.footballPlayer">
  2. <property name="name" value="Messi"></property>
  3. <property name="team" value="Barcelona"></property>
  4. </bean>

创建类beanFactoryPostProcessorImpl,实现接口BeanFactoryPostProcessor:

  1. public class beanFactoryPostProcessorImpl implements BeanFactoryPostProcessor{
  2. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  3. System.out.println("beanFactoryPostProcessorImpl");
  4. BeanDefinition bdefine=beanFactory.getBeanDefinition("messi");
  5. System.out.println(bdefine.getPropertyValues().toString());
  6. MutablePropertyValues pv = bdefine.getPropertyValues();
  7. if (pv.contains("team")) {
  8. PropertyValue ppv= pv.getPropertyValue("name");
  9. TypedStringValue obj=(TypedStringValue)ppv.getValue();
  10. if(obj.getValue().equals("Messi")){
  11. pv.addPropertyValue("team", "阿根延");
  12. }
  13. }
  14. bdefine.setScope(BeanDefinition.SCOPE_PROTOTYPE);
  15. }
  16. }

调用类:

  1. public static void main(String[] args) throws Exception {
  2. ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  3. footballPlayer obj = ctx.getBean("messi",footballPlayer.class);
  4. System.out.println(obj.getTeam());
  5. }

输出:

PropertyValues: length=2; bean property ‘name’; bean property ‘team’
阿根延

在《PropertyPlaceholderConfigurer应用》提到的PropertyPlaceholderConfigurer这个类就是BeanFactoryPostProcessor接口的一个实现。它会在容器创建bean之前,将类定义中的占位符(诸如${jdbc.url})用properties文件对应的内容进行替换。

发表评论

表情:
评论列表 (有 0 条评论,281人围观)

还没有评论,来说两句吧...

相关阅读