上篇文章中关于.propertis文件的每条记录在xml文件里面配置,如下图
新方法: 项目启动时候自动扫描.propertis里面的每条内容到map中.
配置文件:
<bean id="myPropertyConfigurer" class="com.ass.base.prop.MyPropertyConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>/WEB-INF/config/config.properties</value>
<value>/WEB-INF/config/system.properties</value>
<value>/WEB-INF/config/approval.properties</value>
</list>
</property>
</bean>
类:
package com.ass.base.prop;
import java.util.HashMap;
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;
public class MyPropertyConfigurer extends PropertyPlaceholderConfigurer {
private Map<String, String> myPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory factory, Properties props) throws BeansException {
super.processProperties(factory, props);
myPropertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
myPropertiesMap.put(keyStr, value);
}
}
public String getVal(String name) {
return myPropertiesMap.get(name);
}
}
使用方式:
@Resource
private MyPropertyConfigurer myPropertyConfigurer;
/**
* 获取properties文件值的方法,通过key获取value
* @param key
* @return
* @author wangt 2014年12月5日 上午9:11:39
*/
public String getProp(String key) {
return myPropertyConfigurer.getVal(key);
}