跳到主要内容

自定义环境仓库

DeepSeek V3 中英对照 Custom Environment Repositories

Spring Cloud Config 支持通过创建和集成自定义的 EnvironmentRepository 实现来增强其配置管理功能。这使您能够为应用程序添加独特的配置源。通过实现 Ordered 接口并指定 getOrder 方法,您还可以在复合配置设置中设置自定义仓库的优先级。如果不这样做,自定义仓库默认会被视为具有最低优先级。

以下是如何创建和配置自定义 EnvironmentRepository 的示例:

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();
}
}
java

通过此设置,如果在 Spring 应用程序的配置中激活 custom 配置文件,你的自定义环境仓库将被集成到配置服务器中。例如,在 application.propertiesapplication.yml 中指定 custom 配置文件如下:

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

现在,访问配置服务器:

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

将返回自定义仓库中的默认值,如下所示:

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