我目前正在嘗試將現有的彈簧應用程序移動到彈簧引導,因此重新創建沒有引導的工作。如何將彈簧引導的數據源配置外部化?
我想從外部來源配置一些屬性(如spring.datasource。*)。具體來說就是具有多個屬性文件的文件夾
我成立了創建propertyPlaceholder configurers這樣的配置類:
@Configuration
public class PropertySourceConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer defaultsPlaceHolderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/*-defaults.properties"));
propertyConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyConfigurer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer externalPlaceHolderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyConfigurer.setLocations(new
PathMatchingResourcePatternResolver().getResources("file:/my-config-path/*.properties"));
propertyConfigurer.setOrder(1);
propertyConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyConfigurer;
}
這似乎對大多數事情的工作(如AMQP還是我自己配置屬性),但是當我嘗試使用彈簧數據 - 他們被忽略了。基本上在這些文件中設置spring.datasource.url
(和其他用於自動配置的東西)不起作用。
通過查看PropertySourcesPropertyResolver
的日誌,我發現這些配置器屬於localProperties
組,在尋找spring.datasource.*
時未使用該組。
有沒有辦法解決這個問題或更好的方式來添加外部屬性文件到我的上下文?
我知道我可以設置spring.config.location
做類似的事情,但我無法將命令行屬性傳遞給我的應用程序,並且需要在我的應用程序中執行此配置。 afaik這是不可能的這個屬性。
編輯:設置spring.config.location
:
嘗試1:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CampaignServiceStarter.class);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.config.location", "file:/my-config-path/*.properties");
}
}
嘗試2:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CampaignServiceStarter.class).properties("spring.config.location=file:/my-config-path/*.properties");
}
}
在兩種情況下,外部性質沒有在所有拾取
(甚至在之前工作過的地方,比如amqp config)
只需將「@ PropertySource」添加到您的配置中,請勿添加額外的「PropertySourcesPlaceholderConfigurer」。或者添加一個'ApplicationContextInitializer',添加其他屬性來源。但是你目前的解決方案不會起作用。另外,爲什麼不把所有東西放在'application.properties'中,並讓spring引導管理一切? –
爲什麼不是所有'applicaton.properties'文件:因爲不同的環境(如us/eu/staging,...)需要不同的配置。有沒有辦法與佔位符做到這一點? '@ PropertySources'不支持這個。 – Laures
然後添加'application-us.properties'。 Spring配置文件和彈簧引導利用它來加載配置文件特定的屬性文件。此外,您的application.properties可能很容易因環境而異。我強烈建議閱讀Spring部分參考指南的[本節](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config)。 [第23.3節](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files)解釋了加載順序。 –