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

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" )) ;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值