網站首頁 編程語言 正文
在編寫項目代碼時,我們要求更靈活的配置,更好的模塊化整合。在 Spring Boot 項目中,為滿足以上要求,我們將大量的參數配置在 application.properties 或 application.yml 文件中,通過?@ConfigurationProperties
?注解,我們可以方便的獲取這些參數值
使用 @ConfigurationProperties 配置模塊
假設我們正在搭建一個發送郵件的模塊。在本地測試,我們不想該模塊真的發送郵件,所以我們需要一個參數來「開關」 disable 這個功能。另外,我們希望為這些郵件配置一個默認的主題,這樣,當我們查看郵件收件箱,通過郵件主題可以快速判斷出這是測試郵件
在 application.properties 文件中創建這些參數:
myapp.mail.enabled=true
myapp.mail.default-subject=This is a Test
我們可以使用?@Value
?注解或著使用 Spring?Environment
?bean 訪問這些屬性,是這種注入配置方式有時顯得很笨重。我們將使用更安全的方式(@ConfigurationProperties
?)來獲取這些屬性
@Data
@ConfigurationProperties(prefix = "myapp.mail")
public class MailModuleProperties{
private Boolean enabled = Boolean.TRUE;
private String defaultSubject;
}
@ConfigurationProperties
?的基本用法非常簡單:我們為每個要捕獲的外部屬性提供一個帶有字段的類。請注意以下幾點:
- 前綴定義了哪些外部屬性將綁定到類的字段上
- 根據 Spring Boot 寬松的綁定規則,類的屬性名稱必須與外部屬性的名稱匹配
- 我們可以簡單地用一個值初始化一個字段來定義一個默認值
- 類本身可以是包私有的
- 類的字段必須有公共 setter 方法
Spring 寬松綁定規則 (relaxed binding)
Spring使用一些寬松的綁定屬性規則。因此,以下變體都將綁定到 hostName 屬性上:
mail.hostName=localhost
mail.hostname=localhost
mail.host_name=localhost
mail.host-name=localhost
mail.HOST_NAME=localhost
如果我們將 MailModuleProperties 類型的 bean 注入到另一個 bean 中,這個 bean 現在可以以類型安全的方式訪問那些外部配置參數的值。
但是,我們仍然需要讓 Spring 知道我們的 @ConfigurationProperties 類存在,以便將其加載到應用程序上下文中(?面試還不知道 BeanFactory 和 ApplicationContext 的區別?)
激活 @ConfigurationProperties
對于 Spring Boot,創建一個 MailModuleProperties 類型的 bean,我們可以通過下面幾種方式將其添加到應用上下文中
首先,我們可以通過添加 @Component 注解讓 Component Scan 掃描到
@Component
@ConfigurationProperties(prefix ="myapp.mail")
class MailModuleProperties{
//....
}
?
很顯然,只有當類所在的包被 Spring?@ComponentScan
?注解掃描到才會生效,默認情況下,該注解會掃描在主應用類下的所有包結構
我們也可以通過 Spring 的 Java Configuration 特性實現同樣的效果:
@Configuration
class PropertiesConfig{
@Bean
public MaillModuleProperties maillModuleProperties(){
return new MailModuleProperties();
}
}
只要 MailModuleConfiguration 類被 Spring Boot 應用掃描到,我們就可以在應用上下文中訪問 MailModuleProperties bean
我們還可以使用?@EnableConfigurationProperties
?注解讓我們的類被 Spring Boot 所知道,在該注解中其實是用了@Import(EnableConfigurationPropertiesImportSelector.class)
?實現,大家可以看一下
@Configuration
@EnableConfigurationProperties(MaillModuleProperties.class)
class PropertiesConfig{
}
激活一個 @ConfigurationProperties 類的最佳方式是什么?
所有上述方法都同樣有效。然而,我建議模塊化你的應用程序,并讓每個模塊提供自己的
@ConfigurationProperties
?類,只提供它需要的屬性,就像我們在上面的代碼中對郵件模塊所做的那樣。這使得在不影響其他模塊的情況下重構一個模塊中的屬性變得容易。因此,我不建議在應用程序類本身上使用?
@EnableConfigurationProperties
,如許多其他教程中所示,是在特定于模塊的 @Configuration 類上使用@EnableConfigurationProperties
,該類也可以利用包私有的可見性對應用程序的其余部分隱藏屬性。
無法轉換的屬性
如果我們在 application.properties 屬性上定義的屬性不能被正確的解析會發生什么?假如我們為原本應該為布爾值的屬性提供的值為 'foo':
myapp.mail.enabled=foo
默認情況下,Spring Boot 將會啟動失敗,并拋出異常:
Failed to bind properties under 'myapp.mail.enabled' to java.lang.Boolean:
Property: myapp.mail.enabled
Value: foo
Origin: class path resource [application.properties]:1:20
Reason: failed to convert java.lang.String to java.lang.Boolean
當我們為屬性配置錯誤的值時,而又不希望 Spring Boot 應用啟動失敗,我們可以設置?ignoreInvalidFields
?屬性為 true (默認為 false)
@Data
@ConfigurationProperties(prefix = "myapp.mail",ignoreInvalidFields = true)
public class MailModuleProperties{
private Boolean enabled = Boolean.TRUE;
}
這樣,Spring Boot 將會設置 enabled 字段為我們在 Java 代碼里設定好的默認值。如果我們沒有設置默認值,enabled 將為 null,因為這里定義的是 boolean 的包裝類 Boolean
未知的屬性
和上面的情況有些相反,如果我們在 application.properties 文件提供了 MailModuleProperties 類不知道的屬性會發生什么?
myapp.mail.enabled=true
myapp.mail.default-subject=This is a Test
myapp.mail.unknown-property=foo
默認情況下,Spring Boot 會忽略那些不能綁定到?@ConfigurationProperties
?類字段的屬性
然而,當配置文件中有一個屬性實際上沒有綁定到?@ConfigurationProperties
?類時,我們可能希望啟動失敗。也許我們以前使用過這個配置屬性,但是它已經被刪除了,這種情況我們希望被觸發告知手動從 application.properties 刪除這個屬性
為了實現上述情況,我們僅需要將?ignoreUnknownFields
?屬性設置為 false (默認是 true)
@Data
@ConfigurationProperties(prefix="myapp.mail",ignoreUnknownFields=false)
class MailModuleProperties{
private Boolean enabled = Boolean.TRUE;
private String defaultSubject;
}
現在,應用啟動時,控制臺會反饋我們異常信息
Binding to target [Bindable@cf65451 type = com.example.configurationproperties.properties.MailModuleProperties, value = 'provided', annotations = array<Annotation>[@org.springframework.boot.context.properties.ConfigurationProperties(value=myapp.mail, prefix=myapp.mail, ignoreInvalidFields=false, ignoreUnknownFields=false)]] failed:
Property: myapp.mail.unknown-property
Value: foo
Origin: class path resource [application.properties]:3:29
Reason: The elements [myapp.mail.unknown-property] were left unbound.
棄用警告??(Deprecation Warning)
ignoreUnknownFields
?在未來 Spring Boot 的版本中會被標記為 deprecated,因為我們可能有兩個帶有?@ConfigurationProperties
?的類,同時綁定到了同一個命名空間 (namespace) 上,其中一個類可能知道某個屬性,另一個類卻不知道某個屬性,這樣就會導致啟動失敗
啟動時校驗 @ConfigurationProperties
如果我們希望配置參數在傳入到應用中時有效的,我們可以通過在字段上添加?bean validation
?注解,同時在類上添加?@Validated
注解
@ConfigurationProperties(prefix = "myapp.mail")
@Validated
@Data
class MailModuleProperties{
@NotNull
private Boolean enabled;
@NotEmpty
private String defaultSubject;
}
如果我們忘記在 application.properties 文件設置 enabled 屬性,并且設置 defaultSubject 為空
myapp.mail.default-subject=
應用啟動時,我們將會得到?BindValidationException
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'myapp.mail' to com.example.configurationproperties.properties.MailModuleProperties failed:
Property: myapp.mail.enabled
Value: null
Reason: must not be null
Property: myapp.mail.defaultSubject
Value: null
Reason: must not be empty
當然這些默認的驗證注解不能滿足你的驗證要求,我們也可以自定義注解
如果你的驗證邏輯很特殊,我們可以實現一個方法,并用 @PostConstruct 標記,如果驗證失敗,方法拋出異常即可, 關于 @PostConstruct,可以查看?Spring Bean 的生命周期,我從哪里來?
復雜屬性類型
多數情況,我們傳遞給應用的參數是基本的字符串或數字。但是,有時我們需要傳遞諸如 List 的數據類型
List 和 Set
假如,我們為郵件模塊提供了一個 SMTP 服務的列表,我們可以添加該屬性到 MailModuleProperties 類中
@Data
@Component
@ConfigurationProperties(prefix="myapp.maill")
public class MailModuleProperties{
private List<String> smtpServers;
}
我們有兩種方式讓 Spring Boot 自動填充該 list 屬性
application.properties
在 application.properties 文件中以數組形式書寫
myapp.mail.smtpServers[0]=sever1
myapp.mail.smtpServers[1]=server2
application.yml
YAML 本身支持 list 類型,所以可以在 application.yml 文件中添加:
myapp:
mail:
smtp-servers:
- server1
- server2
set 集合也是這種方式的配置方式,不再重復書寫。另外YAML 是更好的閱讀方式,層次分明,所以在實際應用中更推薦大家使用該種方式做數據配置
Duration
Spring Boot 內置支持從配置參數中解析 durations (持續時間),官網文檔?給出了明確的說明
@Data
@ConfigurationProperties(prefix="myapp.mail")
class MailModuleProperties{
private Duration pauseBetweenMails;
}
我們既可以配置毫秒數數值,也可配置帶有單位的文本:
myapp.mail.pause-between-mails=5s
官網上已明確說明,配置 duration 不寫單位,默認按照毫秒來指定,我們也可已通過 @DurationUnit 來指定單位:
@Data
@ConfigurationProperties(prefix = "myapp.mail")
class MailModuleProperties{
@DurationUnit(ChronoUnit.SECONDS)
pirvate Duration pauseBetweenMails;
}
常用單位如下:
-
ns
?for nanoseconds (納秒) -
us
?for microseconds (微秒) -
ms
?for milliseconds (毫秒) -
s
?for seconds (秒) -
m
?for minutes (分) -
h
?for hours (時) -
d
?for days (天)
DataSize
與 Duration 的用法一毛一樣,默認單位是 byte (字節),可以通過 @DataSizeUnit 單位指定:
@Data
@ConfigurationProperties(prefix = "myapp.mail")
class MailModuleProperties{
@DataSizeUnit(DataUnit.MEGABYTES)
private DataSize maxAttachmentSize = DataSize.ofMegabytes(2);
}
添加配置
myapp.mail.max-attachment-size=1MB
但是,我測試的時候打印出來結果都是以 B (bytes) 來顯示
常見單位如下:
-
B
?for bytes -
KB
?for kilobytes -
MB
?for megabytes -
GB
?for gigabytes -
TB
?for terabytes
自定義類型
有些情況,我們想解析配置參數到我們自定義的對象類型上,假設,我們我們設置最大包裹重量:
myapp.mail.max-attachment-weight=5kg
在 MailModuleProperties 中添加 Weight 屬性
@Data
@ConfigurationProperties(prefix="myapp.mail")
class MailModuleProperties{
private Weight maxAttachmentWeight;
}
我們可以模仿 DataSize 和 Duration 創造自己的 converter (轉換器)
class WeightConverter implements Converter<String,Weight>{
@Override
public Weight convert(String source){
// create and return a Weight object from the String
}
}
將其注冊到 Spring Boot 上下文中
@Configuration
class PropertiesConfig{
@Bean
@ConfigurationPropertiesBinding
public WeightConverter weightConverter(){
return new WeightConverter();
}
}
@ConfigurationPropertiesBinding
?注解是讓 Spring Boot 知道使用該轉換器做數據綁定
使用 Spring Boot Configuration Processor 完成自動補全
我們向項目中添加依賴:
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Gradle
annotationProcessor 'org.springframework.boot:spring-boot-configuration-process
重新 build 項目之后,configuration processor 會為我們創建一個 JSON 文件:
?
這樣,當我們在 application.properties 和 application.yml 中寫配置的時候會有自動提醒:
標記配置屬性為 Deprecated
configuration processor 允許我們標記某一個屬性為 deprecated
@DeprecatedConfigurationProperty(reason="change name",replacement="none")
public String getDefaultSubject(){
return defaultSubject;
}
我們可以通過添加?@DeprecatedConfigurationProperty
?注解到字段的 getter 方法上,來標示該字段為 deprecated,重新 build 項目,看看 JSON 文件發生了什么?
當我們再編寫配置文件時,已經給出了明確 deprecated 提示:
總結
Spring Boot 的?@ConfigurationProperties
?注解在綁定類型安全的 Java Bean 時是非常強大的,我們可以配合其注解屬性和?@DeprecatedConfigurationProperty
?注解獲取到更友好的編程方式,同時這樣讓我們的配置更加模塊化。
附加說明
以為?@ConfigurationProperties
?注解滿足我們的全部需要了嗎?其實不然,Spring 官網明確給出了該注解和?@Value
?注解的對比:
如果使用 SpEL 表達式,我們只能選擇?@Value
?注解
另外我之前在閱讀 RabbitMQ 源碼時,發現 RabbitProperties 類充分的利用了?@ConfigurationProperties
?注解特性:
- deprecated
- Duration
- Enum
- 嵌套屬性
感覺自己后知后覺,最近在思考,為什么小時候要閱讀和背誦古詩詞,文言文等經典,因為這樣寫文章就可以輕松熟練的引用經典。技術也一樣,各種框架的源碼就是學生時代的古詩詞和文言文,我們要多多查看閱讀,甚至背誦編程思想,這樣就可以寫出越來越優雅的代碼
關于?@ConfigurationProperties
?注解的使用,這里推薦?RabbitMQ Github 源碼,只需看這一個類就可以,知道怎樣充分利用這個注解.
Demo 代碼獲取,回復公眾號「demo」,打開鏈接查看對應的子文件夾即可
?
?
?
?
?
?
原文鏈接:https://blog.csdn.net/baidu_37366055/article/details/109990010
相關推薦
- 2022-08-14 win?sever?2022如何占用操作主機角色_win服務器
- 2022-08-23 Pandas?Matplotlib保存圖形時坐標軸標簽太長導致顯示不全問題的解決_python
- 2024-01-16 Oracle的取整函數
- 2022-08-28 go?zero微服務高在請求量下如何優化_Golang
- 2022-06-30 Oracle在PL/SQL中使用存儲過程_oracle
- 2022-06-04 Android基于Fresco實現圓角和圓形圖片_Android
- 2022-07-24 基于python實現雙向鏈表_python
- 2022-06-06 ?Redis?串行生成順序編碼的方法實現_Redis
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支