通常情况下,我们读取配置文件只需要在spring配置文件中配置如下即可:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:api.properties" />
<property name="fileEncoding" value="utf-8" />
</bean>
这样就可以在项目中使用@value读取到配置了。
但是很多情况下,可能我们需要直接读取配置文件,譬如异步任务中读取到一些配置,那么这样就不是很方便,因此我们可以通过继承PropertyPlaceholderConfigurer实现。
CustomPropertyConfigurer.java
/**
* 通用配置文件holder
*/
public class CustomPropertyConfigurer extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertiesCopy = new HashMap<>();
/**
* 重载处理类的方法 用于得到配置文件的拷贝
* @param beanFactoryToProcess
* @param props
* @throws BeansException
*/
@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));
propertiesCopy.put(keyStr,value);
}
}
public static String getProperty(String key) {
return propertiesCopy.get(key);
}
public static String getProperty(String key, String defaultStr) {
String val = propertiesCopy.get(key);
if (!StringUtils.isEmpty(val)) {
return val;
}
return defaultStr;
}
public static Integer getIntProperty(String key) {
String val = propertiesCopy.get(key);
if (!StringUtils.isEmpty(val)) {
Integer.valueOf(val);
}
return null;
}
public static Integer getIntProperty(String key, Integer defaultInt) {
try {
String val = propertiesCopy.get(key);
if (!StringUtils.isEmpty(val)) {
return Integer.valueOf(val);
}
} catch (Exception e) {
//
}
return defaultInt;
}
/**
* 得到所有配置 不可变
* @return
*/
public static Map<String, String> getPropMapCopy() {
return Collections.unmodifiableMap(propertiesCopy);
}
/**
* 如果配置文件需要加解密 则重写此方法即可 可以对指定部分的配置进行加解密
*
@Override
protected void convertProperties(Properties props) {
Enumeration<?> propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
String convertedValue = convertProperty(propertyName, propertyValue);
if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
props.setProperty(propertyName, convertedValue);
}
}
}
*/
/* 如果是需要对所有的配置进行统一处理 则重写这个方法 如果是部分处理,则重写上面的
protected String convertPropertyValue(String originalValue) {
return originalValue;
}*/
}
spring-context.xml
<bean id="propertyConfigurer" class="com.mcc.api.support.CustomPropertyConfigurer">
<property name="locations" value="classpath:api.properties" />
<property name="fileEncoding" value="utf-8" />
</bean>
如此一来,在不影响原来使用的基础上,就可以很方便的通过静态方法获取到配置文件了。也无需自定义PropertieUtil来读取了。