前言
系统参数我们都喜欢用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);
//省略业务代码,静态方法
}