题外:
- springboot配置优先级(默认)
命令行参数 > 操作系统环境变量 > 应用外的配置文件 > 应用内的配置文件 - springcloud 配置优先级(默认)
配置中心 > 命令行参数 > 本地application.yml > 本地bootstrap.yml
配置配置中心优先级等级的三个配置
spring:
cloud:
config:
# 覆盖系统属性 默认为true
override-system-properties: true
# 默认为true
allow-override: true
# 默认为false
override-none: true
源码分析
截取关键片段
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(PropertySourceBootstrapProperties.class)
public class PropertySourceBootstrapConfiguration
implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
private void insertPropertySources(MutablePropertySources propertySources, List<PropertySource<?>> composite) {
//composite是配置中心的配置
MutablePropertySources incoming = new MutablePropertySources();
List<PropertySource<?>> reversedComposite = new ArrayList<>(composite);
// Reverse the list so that when we call addFirst below we are maintaining the same order of PropertySources Wherever we call addLast we can use the order in the List since the first item will end up before the rest
//调用了倒序排序,这是为了方便在调用addLast和addFirst方法的时候保证顺序是一致的,下面reversedComposite是调用addFirst和addAfter, composite是调用addLast和addBefore
Collections.reverse(reversedComposite);
for (PropertySource<?> p : reversedComposite) {
incoming.addFirst(p);
}
PropertySourceBootstrapProperties remoteProperties = new PropertySourceBootstrapProperties();
Binder.get(environment(incoming)).bind("spring.cloud.config", Bindable.ofInstance(remoteProperties));
//这个分支是远程覆盖本地,默认走这个分支
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;
}
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);
}
}
}
总结上面的配置顺序
allowOverride =false || (overrideNone =false && overrideSystemProperties=true) ** --> ** propertySources.addFirst§;
propertySources中 远程的在前面 本地的在后面
运行结果:远程的生效
overrideNone =true ** --> ** propertySources.addLast§;
propertySources中 本地的在前面 远程的在后面
运行结果:本地的生效
==》得出结论,propertySources 前面加载的属性不会被后面的属性覆盖
不做配置默认是远程覆盖本地
配置本地覆盖远程:overrideNone =true && allowOverride =true 只需配置两个就行
想要实现命令优先级》配置中心》本地配置
overrideNone =false && allowOverride=true && overrideSystemProperties =false