SpringCloud 本地配置覆盖配置中心的配置
本地开发使用Consul时,发现需要临时修改一个配置中心的配置,由于开发环境配置中心还有其他人在使用,所以要实现本地配置能覆盖远程配置。
将下列配置,写入远程配置中心中,(以我的为例,是写入远程dev环境配置文件中)
点击查看代码
spring:
cloud:
config:
allow-override: true # 为true 远程配置优先级最低,本地配置可覆盖远程
override-none: true #为true不覆盖本地
overrideSystemProperties: false # 为true,远程配置应覆盖本地配置
本代码涉及的类在spring-cloud-context依赖的org.springframework.cloud.bootstrap.config包中
PropertySourceBootstrapProperties 相关参数默认值如下:

PropertySourceBootstrapConfiguration的insertPropertySources 源码解析
点击查看代码
private void insertPropertySources(MutablePropertySources propertySources, List<PropertySource<?>> composite) {
MutablePropertySources incoming = new MutablePropertySources();
List<PropertySource<?>> reversedComposite = new ArrayList<>(composite);
// 反转列表,以便当我们在下面调用 addFirst 时,我们保持 PropertySources 的相同顺序,
// 无论我们在哪里调用 addLast,我们都可以使用 List 中的顺序,因为第一项将在其余项之前结束
Collections.reverse(reversedComposite);
for (PropertySource<?> p : reversedComposite) {
incoming.addFirst(p);
}
PropertySourceBootstrapProperties remoteProperties = new PropertySourceBootstrapProperties();
// 获取远程配置中的 spring.cloud.config
Binder.get(environment(incoming)).bind("spring.cloud.config", Bindable.ofInstance(remoteProperties));
// 根据consul配置中的 spring.cloud.config属性进行判断
// !不允许覆盖本地 或者 ( !不覆盖本地 && 远程配置应覆盖本地配置 ) 则将远程文件放在第一序列(优先级高)
if (!remoteProperties.isAllowOverride()
|| (!remoteProperties.isOverrideNone() && remoteProperties.isOverrideSystemProperties())) {
for (PropertySource<?> p : reversedComposite) {
propertySources.addFirst(p);
}
return;
}
// 不覆盖本地 则将远程配置放在最后序列(优先级低)
if (remoteProperties.isOverrideNone()) {
for (PropertySource<?> p : composite) {
propertySources.addLast(p);
}
return;
}
// 配置中包含 systemEnvironment
if (propertySources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) {
// !远程配置应覆盖本地配置 则将远程配置放在本地环境配置 之后
if (!remoteProperties.isOverrideSystemProperties()) {
for (PropertySource<?> p : reversedComposite) {
propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, p);
}
}
else {
// 否则 将远程配置放在 本地配置之前
for (PropertySource<?> p : composite) {
propertySources.addBefore(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, p);
}
}
}
else {
//配置中没有 环境配置就 把远程配置加到配置集合里
for (PropertySource<?> p : composite) {
propertySources.addLast(p);
}
}
}

浙公网安备 33010602011771号