此版本仍在开发中,目前尚不稳定。如需最新稳定版本,请使用 Spring Cloud Config 5.0.1spring-doc.cadn.net.cn

自定义环境仓库

Spring Cloud Config 支持通过创建并集成自定义的 EnvironmentRepository 实现来增强其配置管理功能。这使得您能够为应用程序添加独特的配置源。通过实现 Ordered 接口并指定 getOrder 方法,您还可以在复合配置设置中设置自定义仓库的优先级。若未进行此操作,自定义仓库将默认以最低优先级处理。spring-doc.cadn.net.cn

下面是一个如何创建和配置自定义 EnvironmentRepository 的示例:spring-doc.cadn.net.cn

public class CustomConfigurationRepository implements EnvironmentRepository, Ordered {

    @Override
    public Environment findOne(String application, String profile, String label) {
        // Simulate fetching configuration from a custom source
        final Map<String, String> properties = Map.of(
            "key1", "value1",
            "key2", "value2",
            "key3", "value3"
        );
        Environment environment = new Environment(application, profile);
        environment.add(new PropertySource("customPropertySource", properties));
        return environment;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

@Configuration
@Profile("custom")
public class AppConfig {
    @Bean
    public CustomConfigurationRepository customConfigurationRepository() {
        return new CustomConfigurationRepository();
    }
}

在此设置下,如果在您的 Spring 应用程序配置中激活 custom 配置文件,则您的自定义环境仓库将集成到配置服务器中。例如,您可在 application.propertiesapplication.yml 中指定 custom 配置文件,如下所示:spring-doc.cadn.net.cn

spring:
  application:
    name: configserver
  profiles:
    active: custom

现在,正在访问配置服务器:spring-doc.cadn.net.cn

http://localhost:8080/any-client/dev/latest

将返回自定义仓库中的默认值,如下所示:spring-doc.cadn.net.cn

{
  "name": "any-client",
  "profiles": ["dev"],
  "label": "latest",
  "propertySources": [
    {
      "name": "customPropertySource",
      "source": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
      }
    }
  ]
}