我找到了一種方法來實現這一點。開源!
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-12-03 15:09:39
Tan
你想改變什麼? – Andreas
我想改變優先順序。 – Tan
尚未找到解決方案,但您可以通過設計解決一些問題,尤其是在需要處理屬性來源的特定順序時。因此,對於應用程序設置,請始終使用自定義的@PropertySource,因爲它會首先檢查外部,然後檢查內部(這樣您就可以啓動固定的默認設置並可以從外部文件中進行覆蓋)。不要將設置與application.properties混合,因爲9/10將在11之前匹配。 – DoNuT