【问题标题】:Exclude Java System properties and environment variables from SpringBoot configuration从 Spring Boot 配置中排除 Java System 属性和环境变量
【发布时间】:2017-11-17 15:07:16
【问题描述】:

关于SpringBoot的属性解析这里解释:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

我想从机制中排除:

9.  Java System properties (System.getProperties()).
10. OS environment variables.

有可能吗?

谢谢

【问题讨论】:

  • 您有什么特别的理由要这样做吗?只是为了了解上下文

标签: spring spring-boot properties


【解决方案1】:

在实例化 Spring Boot 应用程序时,您可以提供自己的 StandardEnvironment 实现。

例如:

public static void main(String[] args) {
    SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder(Application.class)
            .environment(new StandardEnvironment(){
                @Override
                protected void customizePropertySources(MutablePropertySources propertySources) {
                    // do not add system or env properties to the set of property sources
                }
            });
    applicationBuilder.run(args);
}

或者:

public static void main(String[] args) {
    SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder(Application.class)
            .environment(new StandardEnvironment(){
                @Override
                public Map<String, Object> getSystemEnvironment() {
                    return new HashMap<>();
                }

                @Override
                public Map<String, Object> getSystemProperties() {
                    return new HashMap<>();
                }
            });
    applicationBuilder.run(args);
}

无论哪种方式,您都要确保您的应用程序的属性不包含任何系统或环境属性。

【讨论】:

  • 我发现在集成测试中有用的另一种方法是在配置测试类上显式使用@TestPropertySource(value = "application-test.properties"),然后导入该配置类以强制测试属性在存在任何 java 系统或可能覆盖它们的环境变量。不清楚 OP 是否在测试环境中询问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2018-07-31
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2021-02-09
  • 2022-01-12
相关资源
最近更新 更多