2016-12-03 204 views
3

春天启动的使用被设计为允许值的理智压倒一切的,属性按以下顺序考虑一个PropertySource订单的订货:春季启动:更改PropertySource

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

但我不喜欢这样。我该如何改变它?

+0

你想改变什么? – Andreas

+0

我想改变优先顺序。 – Tan

+0

尚未找到解决方案,但您可以通过设计解决一些问题,尤其是在需要处理属性来源的特定顺序时。因此,对于应用程序设置,请始终使用自定义的@PropertySource,因为它会首先检查外部,然后检查内部(这样您就可以启动固定的默认设置并可以从外部文件中进行覆盖)。不要将设置与application.properties混合,因为9/10将在11之前匹配。 – DoNuT

回答

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