根據文檔@Profile
註釋僅適用於@Component
或@Configuration
。無論如何,您無法獲取關於ContextLoaderListener中的配置文件的信息,因爲尚未加載ApplicationContext。如果你想在應用程序啓動調用你的代碼,我的建議是建立ApplicationListener
,聽ContextRefreshEvent
:
@Component
public class CustomContextListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
Environment environment = contextRefreshedEvent.getApplicationContext().getEnvironment();
if(environment.acceptsProfiles("test")){
System.out.print("Test profile is active");
}
}
}
第一次後應用被初始化這個監聽器將被調用。 如果你要得到以前背景下initilized配置文件信息,您可以創建新的上下文裝載機:
public class ProfileContextListener extends ContextLoaderListener {
@Override
public void contextInitialized(ServletContextEvent event) {
if(isProfileActive("test", event.getServletContext())){
System.out.println("Profile is active");
}
}
private boolean isProfileActive(String profileName, ServletContext context) {
String paramName = "spring.profiles.active";
//looking in web.xml
String paramValue = context.getInitParameter(paramName);
if(paramValue==null) {
//if not found looking in -D param
paramValue = System.getProperty(paramName);
};
if(paramValue==null) return false;
String[] activeProfileArray = paramValue.split(",");
for(String activeProfileName : activeProfileArray){
if(activeProfileName.trim().equals(profileName)) return true;
}
return false;
}
}
要激活你必須添加到您的web.xml專用彈簧環境屬性所需的個人資料 - spring.profiles.active
:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>default,test</param-value>
</context-param>
或者你也可以設置個人資料擲-D JVM選項
-Dspring.profiles.active=default,test
請注意,您可以添加多個以逗號分隔的配置文件名稱。
初始化後,對我來說是晚 – gstackoverflow
** context.getInitParameter( 「spring.profiles.active」)**始終返回null。我啓動應用程序是這樣的:** MVN全新安裝碼頭:運行-Dspring.profiles.active =測試** – gstackoverflow
@gstackoverflow,因爲要得到JVM選項PARAM我們必須應該使用System.getProperty()。代碼已更新。 –