![](/img/trans.png)
[英]How to load environment specific configurations and properties with Spring boot using Maven Profiles and Settings Example
[英]Loading environment properties using Spring profiles
我正在使用Spring, Java, Ant
Web應用程序。 我正在使用Spring性能分析來加載基於環境的屬性。 下面是示例
@Profile("dev")
@Component
@PropertySource("classpath:dev.properties")
public class DevPropertiesConfig{
}
@Profile("qa")
@Component
@PropertySource("classpath:qa.properties")
public class TestPropertiesConfig {
}
@Profile("live")
@Component
@PropertySource("classpath:live.properties")
public class LivePropertiesConfig{
}
在web.xml中 ,我們可以提供配置文件
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
現在,我的查詢針對需要創建單獨的Java類的每種環境。
問題:是否可能只有一個類,例如提供配置文件名稱作為某些綁定參數,例如@Profile({profile})
。
另外,請告訴我是否還有其他更好的選擇可實現相同目標。
一次可能有多個配置文件處於活動狀態,因此沒有單個屬性可以獲取活動配置文件。 一個通用的解決方案是創建一個ApplicationContextInitializer
,它基於活動的配置文件加載其他配置文件。
public class ProfileConfigurationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(final ConfigurableApplicationContext ctx) {
ConfigurableEnvironment env = ctg.getEnvironment();
String[] profiles = env.getActiveProfiles();
if (!ArrayUtils.isEmpty(profiles)) {
MutablePropertySources mps = env.getPropertySources();
for (String profile : profiles) {
Resource resource = new ClassPathResource(profile+".properties");
if (resource.exists() ) {
mps.addLast(profile + "-properties", new ResourcePropertySource(resource);
}
}
}
}
}
諸如此類的事情應該可以解決(在我從頭頂輸入時可能包含錯誤)。
現在,在web.xml
包含一個名為contextInitializerClasses
的上下文參數,並為其指定初始化程序的名稱。
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>your.package.ProfileConfigurationInitializer</param-value>
</context-param>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.