SpringBoot @ConfigurationProperties注解的簡單使用
源碼
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default "";
@AliasFor("value")
String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
使用
向注解中傳入配置文件中的前綴名,如果配置文件如下:
myConfigs:
config1:
field1: f1
field2: f2
field3: f3
那么代碼中的配置類應(yīng)該這樣寫:
@Component
@ConfigurationProperties("myConfigs.config1")
public class MyConfig1 {
String field1;
String field2;
String field3;
}
如上所示,field1, field2, field3三個屬性就被綁定到了對象上。
注意到我們使用了@Component,實際上我們使用配置類都是將其注入到其他類中,所以我們往往將其注冊為Bean。
ignoreInvalidFields默認為false,不合法的屬性的屬性會默認拋出異常;
ignoreUnknownFields默認為true, 未能識別的屬性會被忽略(所以打錯了名字就會被忽略了)
@ConfigurationProperties(prefix="config.prefix", ignoreInvalidFields=true, ignoreUnknownFields=false)
public class MyConfig {
// fields
}
Spring Boot的綁定規(guī)則相當寬松,myField, my-field, my_field等都能識別綁定到myField上。
可以給字段設(shè)定默認值,這樣配置中沒有傳入時會使用默認值。
@ConfigurationProperties("your.prefix")
public class YourConfig {
private String field = "Default"
// setter
}
類的字段必須要有public訪問權(quán)限的setter方法。
在很多情況下public的setter方法時必須的,使用IDEA的話,這里推薦Alt+Insert(Windows, Mac使用Alt+n)生成;當然,想使用Lombok也可以
以上就是SpringBoot @ConfigurationProperties注解的簡單使用的詳細內(nèi)容,更多關(guān)于SpringBoot @ConfigurationProperties注解的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot中的@ConfigurationProperties注解解析
- SpringBoot中@ConfigurationProperties注解的使用與源碼詳解
- 關(guān)于SpringBoot的@ConfigurationProperties注解和松散綁定、數(shù)據(jù)校驗
- SpringBoot2底層注解@ConfigurationProperties配置綁定
- SpringBoot中@ConfigurationProperties注解實現(xiàn)配置綁定的三種方法
- SpringBoot中注解@ConfigurationProperties與@Value的區(qū)別與使用詳解
- Springboot之@ConfigurationProperties注解解讀
相關(guān)文章
Java實現(xiàn)數(shù)組轉(zhuǎn)字符串及字符串轉(zhuǎn)數(shù)組的方法分析
這篇文章主要介紹了Java實現(xiàn)數(shù)組轉(zhuǎn)字符串及字符串轉(zhuǎn)數(shù)組的方法,結(jié)合實例形式分析了Java字符串及數(shù)組相關(guān)的分割、遍歷、追加等操作技巧,需要的朋友可以參考下2018-06-06
關(guān)于Spring的統(tǒng)一功能處理(攔截器)實現(xiàn)
這篇文章主要介紹了關(guān)于Spring的統(tǒng)一功能處理(攔截器)實現(xiàn),每個方法中都要單獨寫用戶登錄驗證的方法,即使封裝成公共方法,也一樣要傳參調(diào)用和在方法中進行判斷,需要的朋友可以參考下2023-05-05
Spring?Data?JPA?在?@Query?中使用投影的方法示例詳解
這篇文章主要介紹了Spring?Data?JPA?在?@Query?中使用投影的方法,大家需要注意如果要在 @Query 中使用投影,必須要主動聲明要查詢的字段,并且主動寫明字段的別名才行,本文通過sql代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-07-07
SpringBoot @JsonDeserialize自定義Json序列化方式
這篇文章主要介紹了SpringBoot @JsonDeserialize自定義Json序列化方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

