Tan
Tan

Reputation: 155

Spring Boot: Change the order of the PropertySource

Spring Boot uses a PropertySource order that is designed to allow sensible overriding of values, properties are considered in the following order:

  1. Command line arguments.
  2. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  3. JNDI attributes from java:comp/env.
  4. Java System properties (System.getProperties()).
  5. OS environment variables.
  6. A RandomValuePropertySource that only has properties in random.*.
  7. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  8. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  9. Application properties outside of your packaged jar (application.properties and YAML variants).
  10. Application properties packaged inside your jar (application.properties and YAML variants).
  11. @PropertySource annotations on your @Configuration classes.
  12. Default properties (specified using SpringApplication.setDefaultProperties).

But I don't like this. How can I change it?

Upvotes: 5

Views: 7801

Answers (1)

Tan
Tan

Reputation: 155

I found a way to achieve this. open source!!!!

App.java (main method)

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;
    }
}

Upvotes: 5

Related Questions