Skip to content
This repository was archived by the owner on Jul 2, 2026. It is now read-only.

@Value vs. @ConfigurationProperties

GeXiangDong edited this page Oct 21, 2019 · 8 revisions

@Value和@ConfigurationProperties两个注解都可以从配置文件获取值并设置到属性中,用法上有区别。

@Value适用一些比较简单的情形,用得比较普遍;而@ConfigurationProperties则可适用一些@Value无法处理更复杂的情形。

myapp:
simple:
name: ABCcount: 15countries: CN,US,UKcomplex:
list:
- id: k1value: hello
- id: k2value: nihao
- id: k3value: konichihanested:
name: Johnaddress:
province: jiangsucity: nanjing

例如上面的配置myapp.simple下的属性都可以用@value获取到,甚至myapp.simple.countries也可以被设置到String[]类型的属性上,但是下面的myapp.complex.list设置的配置,@Value就无法把它转成一个List<Map<String, Object>>类型的属性了,而@ConfigurationProperties可以。甚至myapp.complex.nested还可以被@ConfigurationProperties付值到带有两个属性(province, city)的子类中(参照下面的@ NestedConfigurationProperty注解)

@Value

可处理的类型

只可处理String、数值等简单类型,和简单的数组类型,不能处理map、List等复杂类型

位置

直接写在需要从配置文件读取值的成员变量上即可。 例如:

@ServicepublicclassXxxxService{
@Value("${xxx.yyy: defaultValueHere}")
privateStringxxxYyy;
}

参数

只有一个字符型参数value,用于标记配置文件中的key

参数名称类型默认值说明
valueString从配置文件中哪一项读取值,支持Spring EL

@ConfigurationProperties

可处理的类型

用法

@ConfigurationProperties注解需要写到类上,为该类所有有setter方法的属性从配置文件中读取并付值。 如果类里面的某个属性是

例如:

@ConfigurationPropertiespublicclassxxxYyy{
privateStringname;
@NestedConfigurationPropertyAddressaddress;
publicvoidsetName(Stringname){
this.name = name;
}
publicvoidsetAddress(Addressaddress){
this.address = address;
} }
publicclassAddress{
privateStringprovince;
privateStringcity;
//---略过setter方法
}

参数

参数名称类型默认值说明
ignoreInvalidFieldsbooleanfalsejava中被绑定的属性类型与配置文件中设置的值类型不同时是否忽略
ignoreUnknownFieldsbooleantrueFlag to indicate that when binding to this object invalid fields should be ignored
prefixStringThe name prefix of the properties that are valid to bind to this object.
valueString同prefix,简写,支持Spring EL

前置条件

1、需要增加依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

2、需要先开始使用配置属性的功能(不开启不出错,但不会读取配置并设置到类上)

@EnableConfigurationProperties

@EnableConfigurationProperties需要写在Spring Boot的启动类或配置类上。

从其他配置文件中读取

如果信息配置在了自定义的配置文件中(不是applicaiton.yml),则可以使用@PropertySource注解来告诉spring从哪个文件读取配置信息,例如:

@PropertySource("classpath:configprops.properties")

Clone this wiki locally