2016-12-03 66 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; 
    } 
}