@ConfigurationProperties 與 @Value 都可以從配置文件中獲取配置項。
這兩個註解有什麼區別呢?java
@ ConfigurationProperties | @ Value | |
---|---|---|
功能 | 批量注入 | 單個注入 |
鬆散綁定(鬆散語法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
複雜類型封裝 | 支持 | 不支持 |
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}"
@Value("#{11*2}") private Integer age;
@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: 不是一個合法的電子郵件地址
@Value 並不支持讀取複雜類型的配置項。code