properties java 键值对_在spring中获取properties文件键值对的两种方式

前言

系统参数我们都喜欢用properties格式文件来配置,在applicationContext.xml加入如下配置:

classpath*:/config.properties

file:/c:/htconf/fms/sysconfig.properties

一.spring上下文管理类的调用

在Tomcat启动的时加载到Spring上下文,在spring容器内管理的类获取properties里的键值对比较简单,可以使用@Value注解获取,如下:

/**

* Create Date: 2017年09月01日

* 类功能描述:调用相关外部系统的URL

*/

@Component

public class ExternalSystemParams {

/**

* 费用在线Url

* cost_online.url

*/

@Value("${cost_online.url}")

private String costOnlineUrl;

//去掉了setter和getter

}

二.普通类的调用

但是普通类(不在spring容器里管理的类)如何获取properties键值对呢?可以扩展下PropertyPlaceholderConfigurer类,当加载spring配置文件的时候取得,普通类直接调用,代码如下:

/**

* Create Date: 2017年09月04日

* 类功能描述:自定义Property处理配置类

* 主要用来把spring上下文中properties键值放入Map,供普通类调用

*/

public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {

private static Map ctxPropertiesMap;

@Override

protected void processProperties(ConfigurableListableBeanFactory beanFactory,

Properties props)throws BeansException {

super.processProperties(beanFactory, props);

//load properties to ctxPropertiesMap

ctxPropertiesMap = new HashMap();

for (Object key : props.keySet()) {

String keyStr = key.toString();

String value = props.getProperty(keyStr);

ctxPropertiesMap.put(keyStr, value);

}

}

/**

* PropertiesHandle 会用到

* @param name

* @return

*/

public static Object getContextProperty(String name) {

return ctxPropertiesMap.get(name);

}

}

封装一层,代码如下:

/**

* Create Date: 2017年09月04日

* 类功能描述:从CustomizedPropertyConfigurer的Map中获取properties值

*/

public class PropertiesHandle {

//费用在线

public final static String COST_ONLINE_URL_KEY = "cost_online.url";

/**

* 获取properties值

* @return

*/

public static String getPropertiesStr(String propertyKey){

String costOnlineUrl = (String) CustomizedPropertyConfigurer.getContextProperty(propertyKey);

return costOnlineUrl;

}

}

普通类调用方式如下:

public class CXFSendMessage {

public static final String COST_ONLINE_URL =

PropertiesHandle.getPropertiesStr(PropertiesHandle.COST_ONLINE_URL_KEY);

//省略业务代码,静态方法

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值