转载请标明出处:
原文首发于: 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字符时,会产生乱码。