Spring Boot:更改 PropertySource 的顺序

Tan*_*Tan 5 java spring

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

  1. 命令行参数。
  2. 来自 SPRING_APPLICATION_JSON 的属性(嵌入环境变量或系统属性中的内联 JSON)
  3. 来自 java:comp/env 的 JNDI 属性。
  4. Java 系统属性 (System.getProperties())。
  5. 操作系统环境变量。
  6. 仅具有 random.* 属性的 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 指定)。

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

Tan*_*Tan 4

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

应用监听器.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;
    }
}
Run Code Online (Sandbox Code Playgroud)