Java中如何获取spring中配置的properties属性文件内容

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");

转载于:https://my.oschina.net/weiweiblog/blog/406303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值