@Value在Spring及SpringBoot中的配置及使用

转载请标明出处:
原文首发于: http://www.zhangruibin.com
本文出自 RebornChang的博客

厚颜打广告,博主个人博客地址传送门 ,欢迎来访

@Value注解简介

在开发的过程中,很多东西我们都将其放置在配置文件中,然后使用代码对配置文件进行解析,这样易于系统的维护,减少运维成本。传统的读取配置文件的写法为:
````

Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/config.properties"));
properties.load(bufferedReader);
// 获取key对应的value值
properties.getProperty(String key); 
````

而Spring简化了这个步骤,使用@Value自定义注解的形式进行文件对象内容的读取,其源码为:



        //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //

    package org.springframework.beans.factory.annotation;

    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Value {
        String value();
    }

而其使用方式也很简单:

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

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

这种方式大大简化了项目配置,提高业务中的灵活性。

在Spring中的配置及使用方法

在spring的配置文件中进行bean的配置

Spring的配置文件中写入

<--配置一个名字叫做configProperties的bean,这个bean的位置(locations)是classpath:/config/test.properties-->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
     <property name="locations">  
         <list>  
             <value>classpath:/config/test.properties</value>  
         </list>  
     </property>  
 </bean>  

在/config/test.properties 写入

requestUrl=testUrlFromProperties

在Springboot 的application.yml文件中的配置及使用方法

在application.yml中设置一个名字为testPropertyBean的对象以及testPropertyParam1的参数,设置的方法如下图所示:
代码截图

在Springboot 的application.properties文件中的配置及使用方法

在application.properties文件中的任意地方顶格加入:

aaaa="这里的信息是从文件中读取到的"
bbbb="safdsfsgdsfhsdfhsdfhshsdhsdf"

注解注入方式1

进行这样配置的之后就可以使用@Value注解对文件进行取值,取值的方法为:

     @Value("#{configProperties['requestUrl']}") 
     private String setRequestUrl;

注解注入方式2

  @Value("${bbbb}")
   private String aaaa ;

注意:

1.这个@Value注解只能在方法外面进行参数的注入;

2.设置的参数值为汉字等UTF-8字符时,会产生乱码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值