将配置文件中的数据读取到JAVA代码中使用

环境:Spring + SpringMVC
springVersion:4.2.4.RELEASE

项目中遇到需要将配置文件的数据,读取到JAVA代码中使用的情况。查找了一下资料,发现一个比较好的方法,记录如下:

1、Spring配置文件:

    <!-- 配置文件读取 -->
    <bean class="com.diy.web.common.untils.DIYPropertyPlaceholderConfigurer">
        <property name="locations">
            <array>
                <value>classpath:config.properties</value>
            </array>
        </property>
        <property name="fileEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

2、代码如下:

package com.diy.web.common.untils;

import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.google.common.collect.Maps;

public class DIYPropertyPlaceholderConfigurer extends PropertyPlaceholderSConfigurer {

    private static Map<String, String> map = Maps.newHashMap();

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = String.valueOf(props.get(keyStr));
            map.put(keyStr, value);
        }
    }

    public static String getValue(String name) {
        return map.get(name);
    }

    public static Map<String, String> getValues() {
        return map;
    }

}

3、使用方式如下:

// test为配置文件中的key
String test = DIYPropertyPlaceholderConfigurer.getValue("test");

~~~完~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值