您的位置:首页 > 产品设计 > UI/UE

PropertyPlaceholderConfigurer获取属性文件指定key的value值

2015-11-24 15:58 441 查看
今天花了一天的时间,研究了PropertyPlaceholderConfigurer这个类,首先它的作用是一个资源属性的配置器,能够将BeanFactory的里定义的内容放在一个以.propertis后缀的文件中。那么如何在Java类中获取指定key的value值呢!

步骤:

一:首先创建一个属性文件

二:然后自定义一个属性加载类工具类,必须要extends PropertyPlaceholderConfigurer类,(实际是对PropertyPlaceholderConfigurer类的一个扩展)

public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {

private static Map<String, Object> ctxPropertiesMap;

@Override

protected void processProperties(

ConfigurableListableBeanFactory beanFactoryToProcess,

Properties props) throws BeansException {

super.processProperties(beanFactoryToProcess, props);

ctxPropertiesMap = new HashMap<String, Object>();

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

String keyStr = key.toString();

String value = props.getProperty(keyStr);

ctxPropertiesMap.put(keyStr, value);

}

}

public static Object getContextProperty(String name) {

return ctxPropertiesMap.get(name);

}

public static Object setContextProperty(String name,Object value) {

return ctxPropertiesMap.put(name, value);

}

}

三:然后再spring文件中配置如下

<bean id="propertyConfigurer"

class="com.ljzforum.platform.util.CustomizedPropertyConfigurer">

<property name="locations">

<list>

<value>classpath:context/lxh.properties</value>

</list>

</property>

</bean>

四:最后就是怎么使用了,代码如下

String appId = (String) CustomizedPropertyConfigurer.getContextProperty("app_id");

String app_secret =(String) CustomizedPropertyConfigurer.getContextProperty("app_secret");

很容易吧,如果有什么不懂的问题欢迎大家一起交流学习,本人扣扣2739677514,如有错误,也希望大家指出,谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: