【问题标题】:Custom PropertyPlaceholderConfigurer not resolving自定义 PropertyPlaceholderConfigurer 无法解析
【发布时间】:2019-05-29 12:20:05
【问题描述】:

您好,我是 Spring Boot 的新手(但在我的应用程序中使用 Spring 已经有一段时间了)。我正在尝试使用基于我的SSM Client 的自定义SSM PropertyPlaceholderConfigurer,它从AWS SSM 读取我的属性,以及我的普通application.properties 中的属性。 这段代码在我的 pre-spring-boot 应用程序中运行良好。但是,在新应用程序中,我看到它覆盖了 application.properties。这似乎是一个有据可查的问题。

所以我决定将 application.properties 文件包含在我的自定义 PropertyPlaceholderConfigurer 类中,并将所有属性一起加载,但它仍然无法解析 application.properties 中标有“${}”并由我的自定义解析的任何属性地点。我还需要做什么?

作为替代方案,我尝试让我需要从 SSM 加载的属性通过 EnvironmentPostProcessor 加载,但在加载过程中此时它无法连接到 AWS SSM 服务器(不知道为什么)

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

    答案是使用 EnvironmentPostProcessor。完美运行。见以下代码:

    import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.env.EnvironmentPostProcessor;
    import org.springframework.core.env.ConfigurableEnvironment;
    import org.springframework.core.env.MapPropertySource;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * This class loads SSM parameters base on region and environment
     * Needs to be added to spring.factories class so that it will be invoked. as follow:
     * org.springframework.boot.env.EnvironmentPostProcessor=<full package>.SSMEnvironmentPostProcessor
     * Add the SSM propeties to other properties already set
     */
    
    public class SSMEnvironmentPostProcessor implements EnvironmentPostProcessor {
        private static final String QUOTE = "\"";
    
        @Override
        public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
            SSMClient ssmClient = new SSMClient(DefaultAWSCredentialsProviderChain.getInstance(), System.getProperty("env" +
                    ".region"), new ClientConfiguration());
            ssmClient.init();
            Map<String, Object> parameters = new HashMap<>();
            ssmClient.getParametersByPath("/" + System.getProperty("env"), true).entrySet().stream()
                    .forEach(entry -> parameters.put(entry.getKey(), entry.getValue()));
    
            MapPropertySource mapPropertySource = new MapPropertySource("ssm", parameters);
            environment.getPropertySources().addLast(mapPropertySource);
        }
    
    
    
    
    }
    
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2023-03-04
      • 2013-10-03
      相关资源
      最近更新 更多