當咱們使用 spring boot 在多環境打包,配置屬性在不一樣環境的值不一樣,以下:html
spring: profiles: active: @project.profile@ #根據maven 動態配置profile --- spring: profiles: dev demo: lengleng_dev --- spring: profiles: prd demo: lengleng_prd
或者使用 spring cloud 配置中心 (nacos/config)等java
![webp](http://static.javashuo.com/static/loading.gif)
再有就是 應用配置的同一個屬性,值的來源可能來自配置文件、環境變量、啓動參數等等。 不少狀況因爲如上配置的複雜性,應用在讀取配置的時候,並非咱們預期的值,好比咱們想使用是配置文件 dev 環境的值,卻被環境變量的 或者其餘的數據覆蓋等,這些每每只有等咱們運行時,輸出日誌才能發現錯誤緣由。web
解決方案
spring boot 2.3 Actuator 提供 /actuator/configprops
端點 (以前版本也有此端點,可是行爲發生變化了 /actuator/env
保持一致 ),提供對配置文件屬性跟蹤功能,方便咱們在 spring boot 應用中,實時的獲取配置文件實際加載值。spring
如何使用
引入 actuator 依賴maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
暴露 configprops
端點ide
management: endpoints: web: exposure: include: 'configprops'
對應配置類spring-boot
@Data @Component @ConfigurationProperties("demo") public class DemoConfig { private String username; private String password; }
訪問 Endpoint 實時獲取配置文件的值post
![webp](http://static.javashuo.com/static/loading.gif)
特殊說明
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 在執行單元測試的前置應該經過此端點判斷配置是否和預期一致,避免無用執行條件