Spring容器扩展点之BeanFactoryPostProcessor

本文解析了Spring框架中BeanFactoryPostProcessor的作用及其典型应用场景,特别是在处理配置元数据中的属性占位符,如将${jdbc.driver}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring容器扩展点之BeanFactoryPostProcessor

BeanFactoryPostProcessor?怎么命名与前面讲过BeanPostProcessor那么像呢?
没错,他们都是Spring用于初始化Bean的扩展点,但他们的触发时间可是完全不一样的哦。BeanFactoryPostProcessor的执行时间是在Spring容器对bean进行实例化之前,而BeanPostProcessor的时间则是在Spring容器对bean进行实例化之后。
BeanFactoryPostProcessor允许对bean的定义(配置的元数据)进行修改。例如我们常见的下列配置:

<!--加载配置文件-->
<context:property-placeholder        location="classpath:jdbc.properties"/>

<!--配置c3p0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

在以上对于数据库的配置中,我们引用了配置文件jdbc.properties中的值

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///BookManager
jdbc.user = root
jdbc.password =123

那么问题来了,在Spring将bean实例化时是如何将配置元数据中的${jdbc.driver}替换成真实的com.mysql.jdbc.Driver的呢?这便就是BeanFactoryPostProcessor在Spring容器中的最典型的使用场景之一。该处理的实现类为PropertyPlaceholderConfigurer,它实现了接口BeanFactoryPostProcessor中的postProcessBeanFactory方法,负责在bean实例化之前将配置元数据中的如同${jdbc.driver}的配置替换为它真实的值,然后Spring便就可以正常的实例化了。

  • PropertyPlaceholderConfigurerpostProcessBeanFactory方法的实现如下:
/**
    * {@linkplain #mergeProperties Merge}, {@linkplain #convertProperties convert} and
    * {@linkplain #processProperties process} properties against the given bean factory.
    * @throws BeanInitializationException if any properties cannot be loaded
    */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    try {
        // 读取配置中配置的properties文件
        Properties mergedProps = mergeProperties();

        // Convert the merged properties, if necessary.
        convertProperties(mergedProps);

        // Let the subclass process the properties.
        processProperties(beanFactory, mergedProps);
    }
    catch (IOException ex) {
        throw new BeanInitializationException("Could not load properties", ex);
    }
}
  • 其中processProperties方法在PropertyPlaceholderConfigurer中的实现为
/**
    * Visit each bean definition in the given bean factory and attempt to replace ${...} property
    * placeholders with values from the given properties.
    */
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
        throws BeansException {

    StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(props);
    doProcessProperties(beanFactoryToProcess, valueResolver);
}

好了,如果有兴趣的同学可以去仔细看看源码哦,这里只是简单的阐述下BeanFactoryPostProcessor的使用场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值