使用 Arthas 在 Spring 运行时获取配置值和配置来源

背景

众所周之,Spring / Spring Boot 应用的配置注入方式非常多:

  • System Properties / System Env
  • application.properties / application.yaml
  • Spring Profile
  • Spring Cloud Config

还有很多配置注入的方式你可以参阅 中文文档,可谓是令人眼花缭乱。

获取运行时具体配置

对于开发人员来说,在运行时怎样确定某个配置是否生效?它的具体值是什么?

通过 Arthas,只要一行命令就可以获取到。

例如,获取 server.port 的具体值:

vmtool --action getInstances --className org.springframework.context.ConfigurableApplicationContext --express 'instances[0].getEnvironment().getProperty("server.port")'@String[7001]

获取具体的配置来源

但是这个配置是从哪里来的?

  1. 对于 spring boot 应用,可以打开一个新的 terminal 窗口,执行 telnet 127.0.0.1 3658 连接上Arthas。
  2. 直接 watch 下面的函数。
  3. 在原来窗口用上面的 vmtool 命令来获取 server.port 的值。

watch 返回结果中可以看到,server.port 值来源于 application.yml

watch org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource findConfigurationPropertyPress Q or Ctrl+C to abort.Affect(class count: 1 , method count: 2) cost in 217 ms, listenerId: 5method=org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource.findConfigurationProperty location=AtExitts=2023-11-27 16:08:07.696; [cost=0.327042ms] result=@ArrayList[    @Object[][isEmpty=false;size=1],    @ConfigurationPropertySourcesPropertySource[ConfigurationPropertySourcesPropertySource {name='configurationProperties'}],    @ConfigurationProperty[[ConfigurationProperty@18fb3ec9 name = server.port, value = 7001, origin = class path resource [application.yml] - 2:9]],]

Arthas Idea Plugin 快捷操作

在社区 @汪吉 开发的 Arthas Idea Plugin 中,可以很方便获取单个配置值,或者获取全部配置值。

Arthas Idea 插件

总结

使用 Arthas 在 Spring Boot 运行时获取其配置属性值,以及配置来源的步骤如下:

  1. vmtool 来获取 Spring Context。
  2. 调用 env.getEnvironment().getProperty 来获取具体的值。
  3. 通过 watch Spring Boot 内部的 findConfigurationProperty 函数来获取具体的配置来源,

Ref:https://mp.weixin.qq.com/s/o-A0MtrpkPqmDfV-Ir46sw