Skip to content

@Value vs. @ConfigurationProperties

gexiangdong edited this page Nov 18, 2018 · 8 revisions

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

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

@Value

可处理的类型

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

位置

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

@Service
public class XxxxService{
    @Value("xxx.yyy")
    private String xxxYyy;
}

参数

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

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

@ConfigurationProperties

可处理的类型

用法

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

例如:

@ConfigurationProperties
public class xxxYyy{
   private String name;
   @NestedConfigurationProperty Address address;

   public void setName(String name){
      this.name = name;
   }
   
   public void setAddress(Address address){
      this.address = address;
   } 
}

public class Address{
    private String province;
    private String city;
   
    //---略过setter方法
}

参数

参数名称 类型 默认值 说明
ignoreInvalidFields boolean false java中被绑定的属性类型与配置文件中设置的值类型不同时是否忽略
ignoreUnknownFields boolean true Flag to indicate that when binding to this object invalid fields should be ignored
prefix String The name prefix of the properties that are valid to bind to this object.
value String 同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