在Spring项目中使用@Value注解引入配置文件中的参数

如题所示,有时候我们的一些配置并不能在代码中“写死”,而是需要动态配置在配置文件中。这样可以使得以后需要修改该参数时只需要修改配置文件中的参数值即可,而不需要修改代码。具体配置如下:

(1)在Spring的配置文件中添加以下配置用于引入参数所在的文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< bean  id = "configProperties"
     class = "org.springframework.beans.factory.config.PropertiesFactoryBean" >
     < property  name = "locations" >
         < list >
             < value >classpath:jdbc.properties</ value >
             < value >classpath:article.properties</ value >
         </ list >
     </ property >
</ bean >
 
< bean  id = "propertyConfigurer"
     class = "org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer" >
         < property  name = "properties"  ref = "configProperties"  />  
</ bean >

注:如果想在Controller中也使用@Value注解引入配置文件中的参数的话,那么需要将上面的“propertyConfigurer”这个bean在SpringMVC的配置文件中也重复复制一遍,也就是:

1
2
3
4
< bean  id = "propertyConfigurer"
     class = "org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer" >
         < property  name = "properties"  ref = "configProperties"  />  
</ bean >

(2)article.properties文件的具体内容如下:

1
test.author=zifangsky

(3)测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package  cn.zifangsky.controller;
 
import  org.springframework.beans.factory.annotation.Value;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public  class  TestController {
     
     @Value ( "#{configProperties['test.author']}" )
     private  String author;
     
     @RequestMapping ( "/test.html" )
     public  void  test(){
         System.out.println( "---------------" );
         System.out.println( "测试: "  + author);
     }
}

可以看出,这里使用了@Value注解,其语法如下:

@Value(“#{configProperties[‘参数名’]}”)

当然,还有一种简写的语法是:

@Value(“${参数名}”)

也就是说上面加载参数那里也可以这样使用:

1
2
@Value ( "${test.author}" )
private  String author;

(4)最后输出如下:

1
2
---------------
测试: zifangsky



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1889581,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值