用spring@Value注解实现常量功能

之前的博客中提到过如何通过 java.util.ResourceBundle  java.util.Properties 类通过读取 key-value文件的形式实现常量功能。其实 spring 已经通过 @Value 注解实现,下面看看如何使用。

 

1.创建.properties文件:

在如下目录创建 keyvalue.properties 文件 src/main/resources/META-INF/spring/keyvalue.properties,写入如下内容:

test.value=iloveyou

 

2.配置文件中将.properties文件引入:

applicationContext.xml 配置文件中加入如下内容:

1
2
3
4
5
6
7
8
9
10
< bean  id = "configProperties"  class = "org.springframework.beans.factory.config.PropertiesFactoryBean" >
   < property  name = "locations" >
     < list >
      < value >classpath*:META-INF/spring/*.properties</ value >
    </ list >
  </ property >
</ bean >
< bean  id = "propertyConfigurer"  class = "org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer" >
   < property  name = "properties"  ref = "configProperties" />
</ bean >

这里需要注意的是两个<bean>  id 都可以自定义,第一个<property> 中指定 .properties 文件的路径,第二个<property> 中的 ref 要和第一个<bean>  id 对应。

 

3.使用@Value注解:

   引入Value 类,在需要取值的属性上方加上 @Value 注解,其中注明的 configProperties 和第一个 <bean>中的 id 和第二个 <property> 中的 ref 属性对应,[] 中对应 .properties 文件中相应的 key 值:

1
2
3
4
5
6
7
import  org.springframework.beans.factory.annotation.Value;
  
@Value ( "#{configProperties['test.value']}" )
private  String testValue;
  
System.out.println( "TestValue Is: "  + testValue);
// 输出结果  Test Value Is: iloveyou

出处:http://xitongjiagoushi.blog.51cto.com/9975742/1659051

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值