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

来源:互联网 发布:windows回滚工具 编辑:程序博客网 时间:2024/05/24 00:08
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"?>
<beansxmlns="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-scanbase-package="prs.*"/>
<beanid= "propertyConfigurer"class= "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname= "location">
<value>classpath*:/redis.properties</value>
</property>
<propertyname= "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 classExpostPropertyConfigurerextends PropertyPlaceholderConfigurer {
private staticMap ctxMap= null;
@Override
protected voidprocessProperties(ConfigurableListableBeanFactory beanFactory,
Properties props){
super.processProperties(beanFactory,props);
ctxMap=newHashMap();
for(Object obj:props.keySet()){
ctxMap.put(obj,props.get(obj));
}
}
public staticString getProperties(String key){
return(String) ctxMap.get(key);
}
}
重写processProperties方法,将properties通过静态变量ctxMap保存,然后通过getProperties方法暴露出来,这样在加载了spring上下文中的任意地方都能进行编程式调用:
@Test
public voidcrud() {
System.out.println(ExpostPropertyConfigurer.getProperties("redis.ip"));
}

1 0
原创粉丝点击