首页 > 解决方案 > 尝试从多个源获取属性时如何从 Spring Cloud Config Server 获取一组稳定的属性

问题描述

我需要从 Spring 云配置服务器获取一组稳定的属性。示例:我配置了多个类似 spring.profiles.active=jdbc,git。因此,根据优先级,云配置服务器从 JDBC 获取属性,即从属性表中获取属性,稍后它将从 git 存储库中获取。org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository#findOne(java.lang.String, java.lang.String, java.lang.String, boolean) 方法合并到一个包含 List propertySources 的 Environment 对象中。在这种情况下,列表是多个 PropertySource 对象。问题陈述:我在属性表(JDBC 后端)中有一个名为 app.scheduler.timeout=9000 的属性,并且在 git -profile.properties 文件中也存在与 app.scheduler.timeout=9001 相同的属性。如果您看到最终的 Environment 对象,它将具有两个 PropertySource 中的属性。我知道合并将通过准备引导属性源在 Cloud Config 客户端完成。

有什么方法可以从 Spring Cloud Config Server 本身准备或仅获取一组稳定的 propertySource?即,List 中的单个 propertySource 对象。

注意:在上面的示例中,我只提到了一个属性,但我希望所有属性都应该发生这种合并,以响应发送到云配置客户端。

标签: spring-cloud-configspring-cloud-config-server

解决方案


感谢@ryanjbaxter 提供解决方案。CustomCompositeEnvironmentRepository 应该扩展 ComponsiteEnvironmentRepository。

然后在你的配置类中添加@AutoConfigureBefore(EnvironmentRepositoryConfiguration.class).

你的bean应该定义如下

@Bean
@Primary
@ConditionalOnMissingBean(SearchPathLocator.class)
public CompositeEnvironmentRepository customCompositeEnvironmentRepository() {
    return new CustomCompositeEnvironmentRepository(this.environmentRepos, properties.isFailOnCompositeError());
}

完整的解决方案可在以下 GitHub 位置找到: link


推荐阅读