Spring Cloud Config 通过允许您创建和集成自定义 EnvironmentRepository 实现来支持增强其配置管理。这样就可以向应用程序添加唯一的配置源。通过实现 Ordered 接口并指定 getOrder 方法,您还可以在复合配置设置中设置自定义存储库的优先级。否则,默认情况下,自定义存储库的优先级最低。Spring中文文档

下面是如何创建和配置自定义的示例:EnvironmentRepositorySpring中文文档

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 应用程序的配置中激活配置文件,则自定义环境存储库将集成到配置服务器中。例如,在 或 中指定配置文件,如下所示:customcustomapplication.propertiesapplication.ymlSpring中文文档

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

现在,在以下位置访问配置服务器:Spring中文文档

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

将从自定义存储库返回默认值,如下所示:Spring中文文档

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