@Value

为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。

一、两种使用方法

1、@Value("#{configProperties['key']}")

2、@Value("${key}")

二、配置

2.1 @Value("#{configProperties['key']}")使用

2.1.1配置文件:

  1. 配置方法1:  
  2. <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  3.     <property name="locations">  
  4.         <list>  
  5.             <value>classpath:value.properties</value>  
  6.         </list>  
  7.     </property>  
  8. </bean> 
  1. 配置方法2:  
  2. <util:properties id="configProperties" location="classpath:value.properties"></util:properties>  
注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties


  1. key=1  

ValueDemo.java


  1. @Component  
  2. public class ValueDemo {  
  3.     @Value("#{configProperties['key']}")  
  4.     private String value;  
  5.   
  6.     public String getValue() {  
  7.         return value;  
  8.     }  
  9. }  

2.2 @Value("${key}")使用

2.2.1 配置文件

1、在2.1.1的配置文件基础上增加:


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

2、直接指定配置文件,完整的配置:
  1. <bean id="appProperty"  
  2.           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.     <property name="locations">  
  4.         <array>  
  5.             <value>classpath:value.properties</value>  
  6.         </array>  
  7.     </property>  
  8. </bean>  

ValueDemo.java
  1. @Component  
  2. public class ValueDemo {  
  3.     @Value("${key}")  
  4.     private String value;  
  5.   
  6.     public String getValue() {  
  7.         return value;  
  8.     }  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值