【问题标题】:Spring Boot: Change the order of the PropertySourceSpring Boot:更改 PropertySource 的顺序
【发布时间】:2017-04-18 01:32:14
【问题描述】:

Spring Boot 使用 PropertySource 顺序,该顺序旨在允许合理覆盖值,按以下顺序考虑属性:

  1. 命令行参数。
  2. 来自 SPRING_APPLICATION_JSON 的属性(嵌入在环境变量或系统属性中的内联 JSON)
  3. 来自 java:comp/env 的 JNDI 属性。
  4. Java 系统属性 (System.getProperties())。
  5. 操作系统环境变量。
  6. 仅具有随机属性的 RandomValuePropertySource。*。
  7. 打包 jar 之外的特定于配置文件的应用程序属性(application-{profile}.properties 和 YAML 变体)
  8. 打包在您的 jar 中的特定于配置文件的应用程序属性(application-{profile}.properties 和 YAML 变体)
  9. 打包 jar 之外的应用程序属性(application.properties 和 YAML 变体)。
  10. 应用程序属性打包在您的 jar 中(application.properties 和 YAML 变体)。
  11. @Configuration 类上的@PropertySource 注释。
  12. 默认属性(使用 SpringApplication.setDefaultProperties 指定)。

但我不喜欢这样。我怎样才能改变它?

【问题讨论】:

  • 你想改变什么?
  • 我要更改优先顺序。
  • 也没有找到解决方案,但您可以通过设计解决一些问题,特别是当您需要按特定顺序处理属性源时。因此,对于应用程序设置,请始终使用自定义 @PropertySource,因为它将首先检查外部,然后是内部(因此您可以使用固定默认值启动并可选择从外部文件覆盖)。不要将设置与 application.properties 混合,因为 9/10 将在 11 之前匹配。

标签: java spring


【解决方案1】:

我找到了实现这一目标的方法。开源!!!

App.java(主方法)

public class App {
    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(AppConfig.class);
        SpringApplication app = builder.web(true).listeners(new AppListener()).build(args);
        app.run();
    }
}

AppListener.java

public class AppListener implements GenericApplicationListener {

    public static final String APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME = "applicationConfigurationProperties";

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return ApplicationPreparedEvent.class.getTypeName().equals(eventType.getType().getTypeName());
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationPreparedEvent) {
            ApplicationPreparedEvent _event =  (ApplicationPreparedEvent) event;
            ConfigurableEnvironment env = _event.getApplicationContext().getEnvironment();

            // change priority order application.properties in PropertySources
            PropertySource ps = env.getPropertySources().remove(APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME);
            env.getPropertySources().addFirst(ps);
            // logging.config is my testing property. VM parameter -Dlogging.config=xxx will be override by application.properties
            System.out.println(env.getProperty("logging.config"));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 2021-08-28
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多