淺談SpringBoot2.3 新特配置文件屬性跟蹤
背景
當(dāng)我們使用 spring boot 在多環(huán)境打包,配置屬性在不同環(huán)境的值不同,如下:
spring: profiles: active: @project.profile@ #根據(jù)maven 動(dòng)態(tài)配置profile --- spring: profiles: dev demo: lengleng_dev --- spring: profiles: prd demo: lengleng_prd
或者使用 spring cloud 配置中心 (nacos/config)等

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

特殊說明
configprops Endpoint 會(huì)對(duì)敏感字段默認(rèn)脫敏 ,默認(rèn)關(guān)鍵字類
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"));
}
配置個(gè)性化脫敏規(guī)則
management:
endpoint:
configprops:
keys-to-sanitize:
- 'aaa'
- 'bbb'
當(dāng)配置類的某個(gè)屬性值為空時(shí), 通過 /actuator/configprops 訪問,不會(huì)展示此屬性。
總結(jié)
configprops 端點(diǎn)對(duì)應(yīng) ConfigurationPropertiesReportEndpoint 類, 通過閱讀 可以了解從 PropertySource 獲取配置的技巧
應(yīng)用場(chǎng)景: CI 在執(zhí)行單元測(cè)試的前置應(yīng)該通過此端點(diǎn)判斷配置是否和預(yù)期一致,避免無用執(zhí)行條件
以上源碼可以參考: https://github.com/lltx/spring-boot-course
到此這篇關(guān)于淺談SpringBoot2.3 新特配置文件屬性跟蹤的文章就介紹到這了,更多相關(guān)SpringBoot2.3 文件屬性跟蹤內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring模塊詳解之Spring ORM和Spring Transaction詳解
Spring ORM 是 Spring 框架的模塊之一,旨在簡(jiǎn)化與 JPA、Hibernate、JDO 等 ORM 工具的集成,通過提供統(tǒng)一的 API 和模板類,如 HibernateTemplate 和 JpaTemplate,Spring ORM 使開發(fā)者可以更便捷地執(zhí)行數(shù)據(jù)庫操作,感興趣的朋友跟隨小編一起看看吧2024-09-09
spring中@ControllerAdvice 注解的使用
@ControllerAdvice注解是Spring3.2中新增的注解,主要用于Controller的全局配置,本文就來介紹一下spring中@ControllerAdvice 注解的使用,感興趣的可以了解一下2024-09-09
Spring中BeanUtils.copyProperties的坑及解決
這篇文章主要介紹了Spring中BeanUtils.copyProperties的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
mybatis參數(shù)類型不匹配錯(cuò)誤argument type mismatch的處理方案
這篇文章主要介紹了mybatis參數(shù)類型不匹配錯(cuò)誤argument type mismatch的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Tomcat 實(shí)現(xiàn)WebSocket詳細(xì)介紹
這篇文章主要介紹了Tomcat 如何實(shí)現(xiàn)WebSocket的相關(guān)資料,對(duì)WebSocket協(xié)議通信的過程進(jìn)行了詳細(xì)介紹,需要的朋友可以參考下2016-12-12

