Spring PropertyPlaceholderConfigurer获取属性文件值

PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。

属性文件

以app.properties为例:
配置key-value:

filePath = /Users/loukai/easylife/files/

自定义属性加载工具类

该类必须要继承 PropertyPlaceholderConfigurer类(实际是对PropertyPlaceholderConfigurer类的一个扩展)

public class AppConfigUtil extends PropertyPlaceholderConfigurer{

    private static Map<String, Object> ctxPropertiesMap;

    /**
     * 重写processProperties方法
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        ctxPropertiesMap = new HashMap<String, Object>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            ctxPropertiesMap.put(keyStr, value);
        }
    }

     public static Object getContextProperty(String name) {
            return ctxPropertiesMap.get(name);
     }

     public static Object setContextProperty(String name,Object value) {
            return ctxPropertiesMap.put(name, value);
     }

     public static Map<String, Object> getContextPropertyMap() {
            return ctxPropertiesMap;
        }

}

applicationContext.xml配置

往spring容器中注入bean

<bean id="appConfigUtil" class="com.easylife.core.util.AppConfigUtil">
        <property name="locations">
            <list>
                <value>classpath*:app.properties</value>
            </list>
        </property>
    </bean>

使用

AppConfigUtil.getContextProperty("filePath");



其他相关

关于PropertyPlaceholderConfigurer的使用可以参看:
http://seraph115.iteye.com/blog/435165
http://www.cnblogs.com/yl2755/archive/2012/05/06/2486752.html
spring获取bean:
http://www.cnblogs.com/yangzhilong/p/3949332.html
java读取properties文件:
http://www.cnblogs.com/hafiz/p/5876243.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值