diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java index 5dfca813..a2493d8e 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java @@ -2,23 +2,58 @@ package com.alibaba.cloud.sentinel.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.env.*; -import java.util.Properties; +import java.util.HashMap; +import java.util.Map; /** * Created by zhh on 2019/8/17. */ public class GatewayEnvironmentPostProcessor implements EnvironmentPostProcessor { private final static String SENTINEL_FILTER_ENABLED = "spring.cloud.sentinel.filter.enabled"; - private final static String FILTERS_DISABLED = "filters_disabled"; + private final static String PROPERTY_SOURCE_NAME = "defaultProperties"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication springApplication) { - Properties properties = new Properties(); - properties.setProperty(SENTINEL_FILTER_ENABLED, "false"); - PropertiesPropertySource propertySource = new PropertiesPropertySource(FILTERS_DISABLED, properties); - environment.getPropertySources().addLast(propertySource); + addDefaultPropertySource(environment); } + + private void addDefaultPropertySource(ConfigurableEnvironment environment) { + + Map map = new HashMap(); + + configureDefaultProperties(map); + + addOrReplace(environment.getPropertySources(), map); + } + + private void configureDefaultProperties(Map source) { + // Required Properties + source.put(SENTINEL_FILTER_ENABLED, "false"); + } + + private void addOrReplace(MutablePropertySources propertySources, + Map map) { + MapPropertySource target = null; + if (propertySources.contains(PROPERTY_SOURCE_NAME)) { + PropertySource source = propertySources.get(PROPERTY_SOURCE_NAME); + if (source instanceof MapPropertySource) { + target = (MapPropertySource) source; + for (String key : map.keySet()) { + if (!target.containsProperty(key)) { + target.getSource().put(key, map.get(key)); + } + } + } + } + if (target == null) { + target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); + } + if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { + propertySources.addLast(target); + } + } + + }