在 spring 中,如何獲取一個 key 的值?
applicationContext.getEnvironment().getProperty("swagger.show")
那么 key 的優先級呢?spring 會加載所有的配置文件,獲取 key 的 value 時,會從前往后遍歷這些配置文件,找到了即返回。所以,靠前的優先級高
sc 中加載遠程配置文件的邏輯:
// org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration#initialize @Override public void initialize(ConfigurableApplicationContext applicationContext) { CompositePropertySource composite = new CompositePropertySource( BOOTSTRAP_PROPERTY_SOURCE_NAME); // NacosPropertySourceLocator 實現了這個接口,order 為 0 AnnotationAwareOrderComparator.sort(this.propertySourceLocators); boolean empty = true; ConfigurableEnvironment environment = applicationContext.getEnvironment(); for (PropertySourceLocator locator : this.propertySourceLocators) { PropertySource<?> source = null; // nacos 拉取配置 source = locator.locate(environment); if (source == null) { continue; } logger.info("Located property source: " + source); composite.addPropertySource(source); empty = false; } if (!empty) { MutablePropertySources propertySources = environment.getPropertySources(); String logConfig = environment.resolvePlaceholders("${logging.config:}"); LogFile logFile = LogFile.get(environment); if (propertySources.contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) { propertySources.remove(BOOTSTRAP_PROPERTY_SOURCE_NAME); } // 把遠程配置加入到 environment 中 insertPropertySources(propertySources, composite); reinitializeLoggingSystem(environment, logConfig, logFile); setLogLevels(applicationContext, environment); handleIncludedProfiles(environment); } }
確定配置優先級的邏輯:
// org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration#insertPropertySources private void insertPropertySources(MutablePropertySources propertySources, CompositePropertySource composite) { MutablePropertySources incoming = new MutablePropertySources(); incoming.addFirst(composite); PropertySourceBootstrapProperties remoteProperties = new PropertySourceBootstrapProperties(); Binder.get(environment(incoming)).bind("spring.cloud.config", Bindable.ofInstance(remoteProperties)); if (!remoteProperties.isAllowOverride() || (!remoteProperties.isOverrideNone() && remoteProperties.isOverrideSystemProperties())) { // 遠程配置優先級高 propertySources.addFirst(composite); return; } if (remoteProperties.isOverrideNone()) { // 遠程配置優先級低 propertySources.addLast(composite); return; } if (propertySources .contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { if (!remoteProperties.isOverrideSystemProperties()) { propertySources.addAfter( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, composite); } else { propertySources.addBefore( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, composite); } } else { propertySources.addLast(composite); } }
如果需要使用本地配置覆蓋遠程配置,設置 spring.cloud.config.overrideNone = true