环境: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");
~~~完~~~