自定義環境倉庫
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();
}
}
透過此設定,如果您在 Spring 應用的配置中啟用 custom
profile,您的自定義環境倉庫將被整合到配置服務端。例如,在您的 application.properties
或 application.yml
中指定 custom
profile 如下:
spring:
application:
name: configserver
profiles:
active: custom
現在,訪問配置服務端地址:
https://:8080/any-client/dev/latest
將返回自定義倉庫的預設值,如下所示:
{
"name": "any-client",
"profiles": ["dev"],
"label": "latest",
"propertySources": [
{
"name": "customPropertySource",
"source": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
]
}