BeanFactoryPostProcessor 的使用

116 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

我们知道,BeanFactoryPostProcessor 接口的作用就是Spring 容器提供的一个用来完成“容器扩展机制”的接口。

在Spring 中,其实已经有几个已经写好的BeanFactoryPostProcessor 来为我们提供服务,所以说,在大多数情况下并不需要我们自己去手动实现BeanFactoryPostProcessor。

其中有两个很常用的BeanFactoryPostProcessor 它们分别是:org.springframework.beans.factory.config.PropertyPlaceholderConfigurerorg.springframework.beans.factory.config.PropertyOverrideConfigurer

我们知道,在Spring 中有两种IOC 容器:

  1. 基本的IOC 容器BeanFactory
  2. 较为先进的ApplicationContext

对于它们来说,分别有不同的方式来应用BeanFactoryPostProcessor,接下来我们看看如何进行具体的应用。

对于BeanFactory 应用BeanFactoryPostProcessor

对于BeanFactory,我们需要以手动的方式去应用所有的BeanFactoryPostProcessor,示例代码如下:

// 首先声明一些需要被后处理的BeanFactory 实例
ConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("xxxxxx"));
// 然后再声明一下要使用的BeanFactoryPostProcessor 接口的实例
PropertyPlaceholderConfigurer beanFactoryPostProcessor = new PropertyPlaceholderConfigurer();
beanFactoryPostProcessor.setLocation(new ClassPathResource("xxxxxxx"));
// 执行“post(后处理)”操作
beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);

之前我们提过,在一个容器中可能存在多个BeanFactoryPostProcessor。如果我们系统存在多个BeanFactoryPostProcessor,我们就可以添加更多的类似的相同的代码来应用这些所有的BeanFactoryPostProcessor。

对于ApplicationContext 应用BeanFactoryPostProcessor

对于ApplicationContext 来说情况就比较简单了。对于ApplicationContext,它可以自动识别配置文件中的BeanFactoryPostProcessor,然后将其应用到系统中。

所以,对于ApplicationContext 容器,如果想要加载且使用BeanFactoryPostProcessor,并且我们使用的是xml 的配置方法,我们仅仅需要在xml 文件中配置一下BeanFactoryPostProcessor 就好了。举例代码如下:

<beans>
    <bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name = "locations">
            <list>
                <value>conf/jdbc.properties</value>
                <value>conf/mail.properties</value>
            </list>
        </property>
    </bean>
    ...
</beans>

总结

这篇文章是基于上一篇文章的内容,来说明针对两种不同的IOC 容器应用BeanFactoryPostProcessor 的方式。我们可以尝试着在实际开发中应用一下这些功能,来体验它们带来的便捷之处。