@ConfigurationProperties實現自定義配置繫結
阿新 • • 發佈:2021-08-20
目錄
- @ConfigurationProperties使用
- @ConfigurationProperties特點
- 啟用@ConfigurationProperties
- @ConfigurationProperties與@Value對比
- 使用 Spring Boot Configuration Processor 完成自動補全
@ConfigurationProperties使用
建立一個類,類名上方註解,配置prefix屬性,如下程式碼:
@ConfigurationProperties( prefix = "hello.properties" ) public class MyProperties { private String myKey; private List<String> stringList; private Duration duration; public String getMyKey() { return myKey; } public void setMyKey(String myKey) { this.myKey = myKey; } public List<String> getStringList() { return stringList; } public void setStringList(List<String> stringList) { this.stringList = stringList; } public Duration getDuration() { return duration; } public void setDuration(Duration duration) { this.duration = duration; } @Override public String toString() { return "MyProperties{" + "myKey='" + myKey + '\'' + ", stringList=" + stringList + ", duration=" + duration + '}'; } }
prefix屬性是配置檔案裡的字首,即配置檔案中以
字首 + 變數名`的形式配置一條記錄,來對應類中的一個變數,如下:
hello.properties.myKey=hello
hello.properties.duration=20s
hello.properties.string-list[0]=Acelin
hello.properties.string-list[1]=nice
@ConfigurationProperties特點
寬鬆繫結
如下配置都是可以被識別繫結的:
hello.properties.myKey=hello hello.properties.mykey=hello hello.properties.my-key=hello hello.properties.my_key=hello hello.properties.MY_KEY=hello hello.properties.MY-KEY=hello
支援複雜屬性型別
- 支援從配置引數中解析 durations (持續時間)
hello.properties.duration=20s
- List 和 Set
hello.properties.string-list[0]=Acelin
hello.properties.string-list[1]=nice
啟用@ConfigurationProperties
通過@EnableConfigurationProperties
如果一個配置類只單單用@ConfigurationProperties註解,那麼在IOC容器中是獲取不到properties 配置檔案轉化的bean。我們可以在想要使用該配置類的類上註解@EnableConfigurationProperties,並配置相關的類,即可拿到該裝配好配置的類了。如下所示:
通過@ConfigurationPropertiesScan
該註解有點類似與@CompomentScan註解掃描@Compoment註釋的類相似,也是用來掃描專案中@ConfigurationProperties註解的類,並注入spring容器中。只需將該註解註釋於專案啟動類上即可
其實@ConfigurationProperties更多的作用是將配置檔案中的配置與類中變數對應上來,而上述兩種方式是告訴Spring容器要把這個有配置特性的Bean在程式啟動的時候給創建出來。那談到的建立Bean,我們就會想到Spring建立Bean的各種方式,這些方式的同樣能夠啟用@ConfigurationProperties,詳細請看xxx
@ConfigurationProperties與@Value對比
- | @ConfigurationProperties | @Value |
---|---|---|
功能 | 批量注入配置檔案中的屬性 | 一個個指定 |
鬆散繫結(鬆散語法) | 支援 | 不支援 |
SpEL | 不支援 | 支援 |
JSR303資料效驗 | 支援 | 不支援 |
複雜型別封裝 | 支援 | 不支援 |
使用 Spring Boot Configuration Processor 完成自動補全
當我們在配置檔案中寫官方支援的配置的時候,我們都會發現的有自動補全配置的一個功能,那怎麼也讓我們自己的配置也實現這種功能呢?
其實當你用這個註解的時候,IDE是會提示你這一點的,她會在檔案的上方提示你要可以配置自動補全的功能:
實現的方式就是專案匯入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
然後重新編譯或執行專案:
專案會生產一個json檔案
然後能夠實現自動提示補全配置項的功能了