springBoot @ConfigurationProperties 與@Value的區別

@ConfigurationProperties 與 @Value 都可以從配置文件中獲取配置項。
這兩個註解有什麼區別呢?java

  @ ConfigurationProperties @ Value
功能 批量注入 單個注入
鬆散綁定(鬆散語法) 支持 不支持
SpEL 不支持 支持
JSR303數據校驗 支持 不支持
複雜類型封裝 支持 不支持
  1. 批量注入:前文中使用 @ConfigurationProperties 與@Value 發現,
    @ConfigurationProperties 註解一個類或者方法就能夠將全部的配置項注入到類中。而@Value 則須要將類中的每一個屬性註解才能讀取配置項。
  2. 鬆散綁定(鬆散語法):就是配置文件中的屬性書寫方式。

person.fullName 與類中同名
person.full-name 使用 - 替換大寫
person.full_name 使用 _ 替換大寫spring

@Value 不支持 鬆散綁定 配置文件名必須和類屬性名相同。不然則會報錯app

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.fullNname' in value "${person.fullNname}"
  1. SpEL:EL 表達式
@Value("#{11*2}")
private Integer age;
  1. JSR303數據校驗
@Data
@Component
@ConfigurationProperties(prefix = "person")
@Validated //JSR303數據校驗
public class Person {
    @NotNull //不能爲空
    private String name;
    @Email // 必須爲Email 格式
    private String fullName;
    private Integer age;
    private List<String> list;
    private Map<String,String> map;
    private Dog dog;
}
person:
  name: xiaoming
  full-name: 小明
  age : 11
  list:
    -a -b -c -d
  map: {key1: value1,key2: value2}
  dog:
    name: tom
    age: 3

此時full-name並非一個Email 格式內容,啓動項目報錯:.net

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'person' to com.example.demo.entity.Person failed:

    Property: person.fullName
    Value: 小明
    Origin: class path resource [application.yml]:9:14
    Reason: 不是一個合法的電子郵件地址
  1. 複雜類型封裝: List Map 等。

@Value 並不支持讀取複雜類型的配置項。code

相關文章
相關標籤/搜索