PropertyPlaceholderConfigurer扩展

在Spring项目中,我们常常会使用·PropertyPlaceholderConfigurer·来做一些配置宏替换,例如,XML中配置jdbc时会采用${jdbc.masterUsername}这种形式,在Spring加载时会将${jdbc.masterUsername}替换为property文件中键jdbc.masterUsername对应的值。
但是PropertyPlaceholderConfigurer只支持property文件,而实际应用中可能不止有property文件,或许会用到其他的配置文件,例如com.typesafe.config支持的conf文件配置。因此可以对PropertyPlaceholderConfigurer做如下扩展:

public class MyPropertyPlaceholder extends PropertyPlaceholderConfigurer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyPropertyPlaceholder.class);

    private Resource conf;
    private Config config;

    @Override
    protected String resolvePlaceholder(String placeholder, Properties props) {
        String propVal = super.resolvePlaceholder(placeholder, props);

        if (propVal == null) {
            propVal = config.getString(placeholder);
        }
        return propVal;
    }

    @Override
    protected void loadProperties(Properties props) throws IOException {
        super.loadProperties(props);
        try {
            config = ConfigFactory.parseFile(conf.getFile());
            LOGGER.info("Loading conf file from " + conf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setConf(Resource conf) {
        this.conf = conf;
    }
}

PropertyPlaceholderConfigurer原理是通过BeanFactoryPostProcessor来实现对所有的beanDefinition的property中的${xxx},替换为property文件的xxx键对应的值。
因此扩展的时候,继承PropertyPlaceholderConfigurer,保留PropertyPlaceholderConfigurer之前的location等属性注入property文件,但是扩展了需要的conf文件。重写loadProperties()方法,不仅加载property文件,还加载需要的conf文件。重写resolvePlaceholder()方法,先在Properties去找对应的placeholder(即xxx),如果没有值,则去conf文件中去找键xxx对应值。
在XML中移除PropertyPlaceholderConfigurer的Bean,而使用MyPropertyPlaceholder

    <bean id="propertyConf" class="xxx.xxx.xxx.MyPropertyPlaceholder">
        <property name="location" value="test.properties"/>
        <property name="conf" value="test.conf"/>
    </bean>

MyPropertyPlaceholder不仅可以用来做配置宏替换,还可以作为配置参数的获取,只需要用static属性保存住配置值,对外提供static方法来获取即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值