背景
當我們使用 spring boot 在多環境打包,配置屬性在不同環境的值不同,如下:
spring:
profiles:
active: @project.profile@ #根據maven 動態配置profile
---
spring:
profiles: dev
demo: lengleng_dev
---
spring:
profiles: prd
demo: lengleng_prd
或者使用 spring cloud 配置中心 (nacos/config)等

再有就是 應用配置的同一個屬性,值的來源可能來自組態檔、環境變數、啟動引數等等, 很多情況由于如上配置的復雜性,應用在讀取配置的時候,并不是我們預期的值,比如我們想使用是組態檔 dev 環境的值,卻被環境變數的 或者其他的資料覆寫等,這些往往只有等我們運行時,輸出日志才能發現錯誤原因,
解決方案
spring boot 2.3 Actuator 提供 /actuator/configprops 端點 (之前版本也有此端點,但是行為發生變化了 /actuator/env 保持一致 ),提供對組態檔屬性跟蹤功能,方便我們在 spring boot 應用中,實時的獲取組態檔實際加載值,
如何使用
- 引入 actuator 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 暴露
configprops端點
management:
endpoints:
web:
exposure:
include: 'configprops'
- 對應配置類
@Data
@Component
@ConfigurationProperties("demo")
public class DemoConfig {
private String username;
private String password;
}
- 訪問 Endpoint 實時獲取組態檔的值

特殊說明
- configprops Endpoint 會對敏感欄位默認脫敏 ,默認關鍵字類
public class Sanitizer {
private static final String[] REGEX_PARTS = { "*", "$", "^", "+" };
private static final Set<String> DEFAULT_KEYS_TO_SANITIZE = new LinkedHashSet<>(Arrays.asList("password", "secret",
"key", "token", ".*credentials.*", "vcap_services", "sun.java.command"));
}
- 配置個性化脫敏規則
management:
endpoint:
configprops:
keys-to-sanitize:
- 'aaa'
- 'bbb'
- 當配置類的某個屬性值為空時, 通過 /actuator/configprops 訪問,不會展示此屬性,
總結
-
configprops 端點對應 ConfigurationPropertiesReportEndpoint 類, 通過閱讀 可以了解從
PropertySource獲取配置的技巧 -
應用場景: CI 在執行單元測驗的前置應該通過此端點判斷配置是否和預期一致,避免無用執行條件
-
以上原始碼可以參考: https://github.com/lltx/spring-boot-course
專案推薦: Spring Cloud 、Spring Security OAuth2的RBAC權限管理系統 歡迎關注
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/159111.html
標籤:Java
下一篇:再看python
