hasor icon indicating copy to clipboard operation
hasor copied to clipboard

hasor加载的环境变量 和 spring的环境变量加载的顺序相反

Open lingpeiyong opened this issue 3 years ago • 1 comments

1. 问题表现 比如我在resources/application.yml下定义一个变量 hasor: dataway: authorization: username: adminuser 然后我又在resources/config/application.yml下定义一个变量 hasor: dataway: authorization: username: adminuserInConfig 那么我从 hasor的BuildConfig.envProperties得到的值是adminuser , 而从 @Value("${hasor.dataway.authorization.username:}")得到的值是adminuserInConfig

2.问题可能出现的地方 我个人觉得出现问题的地方是net.hasor.spring.beans.AbstractEnvironmentAware#setupEnvironment这个方法 public Properties setupEnvironment(Environment environment) { this.environment = environment; Properties envProperties = new Properties(); Iterator<PropertySource>> propertySourceIterator = ((StandardEnvironment) environment).getPropertySources().iterator(); while (propertySourceIterator.hasNext()) { PropertySource> propertySource = propertySourceIterator.next(); if ("systemProperties".equalsIgnoreCase(propertySource.getName())) { continue;// this propertySource in Hasor has same one } if ("systemEnvironment".equalsIgnoreCase(propertySource.getName())) { continue;// this propertySource in Hasor has same one } Object source = propertySource.getSource(); if (source instanceof Map) { ((Map, ?>) source).forEach((BiConsumer<Object, Object>) (key, value) -> { if (key == null || value == null) { return; } envProperties.put(key, value); }); } } return envProperties; } 这个方法是取最后一个有对应key的propertySource对应的值(envProperties.put(key, value);不管当前key对应得value有没有值,都重新设置)

而spring的方法org.springframework.core.env.PropertySourcesPropertyResolver#getProperty protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) { if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { if (logger.isTraceEnabled()) { logger.trace("Searching for key '" + key + "' in PropertySource '" + propertySource.getName() + "'"); } Object value = propertySource.getProperty(key); if (value != null) { if (resolveNestedPlaceholders && value instanceof String) { value = resolveNestedPlaceholders((String) value); } logKeyFound(key, propertySource, value); return convertValueIfNecessary(value, targetValueType); } } } if (logger.isTraceEnabled()) { logger.trace("Could not find key '" + key + "' in any property source"); } return null; } 这个方法是取第一个有对应key的propertySource对应的值(value != null时立即返回)

3.还有一个疑惑 if ("systemProperties".equalsIgnoreCase(propertySource.getName())) { continue;// this propertySource in Hasor has same one } if ("systemEnvironment".equalsIgnoreCase(propertySource.getName())) { continue;// this propertySource in Hasor has same one } 这个是为什么,我发现最后从setting里获取的值也没有包括systemProperties 和 systemEnvironment, 但是注释里面说有

lingpeiyong avatar Sep 09 '21 06:09 lingpeiyong

你可以尝试吧 spring 的配置信息全部倒入到 到 hasor

zycgit avatar Dec 19 '21 14:12 zycgit