Micronaut引导上下文缺失BootstrapPropertySourceLocator Bean致自定义配置客户端加载失败
开发目标
- 开发支持从文件系统热重载配置属性的自定义客户端,实现逻辑参考Kubernetes挂载卷形式Secret的处理规则,基于
KubernetesConfigurationClient类完成自定义实现 - 能力规划:完全摆脱对Kubernetes API的依赖,实现Kubernetes集群内以卷挂载形式存在的Secret与ConfigMap的配置全量热重载
- 现有能力缺口:Micronaut官方提供的K8s组件仅支持监听ConfigMap变更、仅能静态读取挂载卷形式的Secret,无法覆盖全量热重载的需求
已编写的代码与配置
核心类定义
@Singleton @Requires(property = ConfigurationClient.ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE) @BootstrapContextCompatible public class MountedVolumeConfigurationClient implements ConfigurationClient { } @ConfigurationProperties(MountedVolumeConfiguration.PREFIX) @BootstrapContextCompatible public class MountedVolumeConfiguration { }
配置文件内容
application.yml
micronaut: application: name: micronaut-service server: port: 8080
bootstrap.yml
micronaut: application: name: micronaut-service config-client: enabled: true poc: client: mounted-volumes: enabled: true config-map-paths: - /configmaps secret-paths: - /secrets
异常表现
- 在
gradle.build中引入依赖implementation("io.micronaut.kubernetes:micronaut-kubernetes-discovery-client:2.2.1-SNAPSHOT")时,所有功能运行正常 - 移除该K8s依赖后,自定义的单例Bean无法被容器加载
问题根因定位
已排查到问题触发逻辑位于DefaultApplicationContext类中:
private BootstrapPropertySourceLocator resolveBootstrapPropertySourceLocator(String... environmentNames) { if (this.bootstrapPropertySourceLocator == null) { BootstrapApplicationContext bootstrapContext = new BootstrapApplicationContext(bootstrapEnvironment, environmentNames); bootstrapContext.start(); if (bootstrapContext.containsBean(BootstrapPropertySourceLocator.class)) { initializeTypeConverters(bootstrapContext); bootstrapPropertySourceLocator = bootstrapContext.getBean(BootstrapPropertySourceLocator.class); } else { bootstrapPropertySourceLocator = BootstrapPropertySourceLocator.EMPTY_LOCATOR; } } return this.bootstrapPropertySourceLocator; }
- 判断逻辑
bootstrapContext.containsBean(BootstrapPropertySourceLocator.class)的返回结果存在差异:引入上述K8s依赖时返回true,移除依赖时返回false
内容的提问来源于stack exchange,提问作者Stephane Paulus
相关产品推荐
相关产品推荐

