您的位置:首页 > 运维架构

properties的获取支持,ResourceBundle 和 PropertyPlaceholderConfigurer 方式

2016-11-07 21:27 375 查看
1.java原生绑定

public void testBundle(){

ResourceBundle bundle = ResourceBundle.getBundle("redis");
//1

System.out.println(bundle.getString("redis.ip"));
//2

}

利用ResourceBundle Java原生工具类进行绑定配置文件资源
只需要将你的redis.properties文件放置到classpath下,然后在运行以上方法时即可动态获取资源,以上1是配置文件路径及文件名,2是配置文件中属性的key。如classpath下有个叫redis.properties的文件,文件的属性如下:

#IP

redis.ip=127.0.0.1

#Port

redis.port=6379
2.PropertyPlaceholderConfigurer
适用场景:依赖于Spring上下文加载类的情况,依赖于spring配置文件。
<?xml version="1.0"
encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan
base-package="prs.*"/>
<bean
id= "propertyConfigurer"
class= "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
>
<property
name= "location"
>
<value>classpath*:/redis.properties</value>
</property>
<property
name= "fileEncoding"
>
<value>UTF-8</value>
</property>
</bean>
</beans>
以上标红的位置是spring对于properties文件动态加载时通用的占位符,只需要修改绿色的部分用于指定配置文件的位置即可。然后在之后的xml中即可作为变量进行引用。
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />

3.暴露属性到变成环境中
以上的引用只能在xml中引用,而不能再编程环境中进行动态调用。为此我们将PropertyPlaceholderConfigurer进行扩展。(此部分参考http://dxp4598.iteye.com/blog/1265360的博文,可以直接参考原著)
定义一个继承了PropertyPlaceholderConfigurer的类ExpostPropertyConfigurer,
public class
ExpostPropertyConfigurer
extends PropertyPlaceholderConfigurer {
private static
Map ctxMap
= null;
@Override
protected void
processProperties(ConfigurableListableBeanFactory beanFactory,
Properties props){
super.processProperties(beanFactory,props);
ctxMap
=new
HashMap();
for
(Object obj:props.keySet()){
ctxMap.put(obj,props.get(obj));
}
}
public static
String getProperties(String key){
return
(String) ctxMap.get(key);
}
}
重写processProperties方法,将properties通过静态变量ctxMap保存,然后通过getProperties方法暴露出来,这样在加载了spring上下文中的任意地方都能进行编程式调用:
@Test
public void
crud() {
System.out.println(ExpostPropertyConfigurer.getProperties("redis.ip"));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐