1. 程式人生 > >六、SpringBoot配置@ConfigurationProperties與@Value區別

六、SpringBoot配置@ConfigurationProperties與@Value區別

環境變量 integer vat lean 映射 int 分享 用法 class

1.@Value的使用

三種用法

技術分享圖片

1 // ${key} 從環境變量、配置文件中取值
2 @Value("${person.last-name}")
3 private String lastName;
4 // #{Spel} Spring支持的表達式
5 @Value("#{11*2}")
6 private Integer age;
7 // 字面量
8 @Value("true")
9 private Boolean boss;

運行結果

技術分享圖片

2.取值比較

技術分享圖片

3.數據校驗編寫

下面是指定了郵箱格式,然後報錯。

技術分享圖片

4.區分使用

如果只是在某個業務邏輯中獲取一下配置文件中的某項值,那就用@Value
如果專門編寫一個JavaBean和配置文件進行映射,那就用@ConfigurationProperties。

技術分享圖片

技術分享圖片

六、SpringBoot配置@ConfigurationProperties與@Value區別