1.通过spring 配置properties文件
1
2
3
4
5
6
7
8
9
|
<!-- 在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码 -->
<beanid="propertyConfigurer"class="PropertyUtils">
<propertyname="locations">
<list>
<value>classpath:shishuocms.properties</value>
<!-- 指定外部文件的编码 -->
</list>
</property>
</bean>
|
2.编写自定义的类PropertyUtils 继承PropertyPlaceholderConfigurer,重写processProperties 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
importjava.util.Enumeration;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Properties;
importorg.apache.commons.lang3.StringUtils;
importorg.apache.log4j.Logger;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;
importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
importcom.shishuo.cms.exception.PropertyIsNullException;
/**
* 属性工具类
*
*
@author Herbert
*
*/
publicclassPropertyUtilsextendsPropertyPlaceholderConfigurer {
publicstaticfinalLogger logger = Logger.getLogger(PropertyUtils.class);
privatestaticMap<String, String> propertyMap;
@Override
protectedvoidprocessProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props)throwsBeansException {
super.processProperties(beanFactoryToProcess, props);
propertyMap =newHashMap<String, String>();
for(Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
propertyMap.put(keyStr, value);
}
}
publicstaticString getValue(String name)throwsPropertyIsNullException {
String value = propertyMap.get(name);
if(StringUtils.isBlank(value)) {
String error ="属性["+ name +"]的值为空";
logger.fatal(error);
thrownewPropertyIsNullException(error);
}else{
returnvalue;
}
}
}
|
3.获取properties 参数值
String val = propertyConfigurer.getValue("oracle.url");