2015-12-23 26 views
0

我需要在應用程序啓動之前執行代碼。如何在contextLoadListener上取決於彈簧配置文件

我已經寫了下面的聽衆(在web.xml中註冊):

Profile("test") 
public class H2Starter extends ContextLoaderListener { 


    @Override 
    public void contextInitialized(ServletContextEvent event) {  
     System.out.println("invoked") 
    }  

} 

我預計只有test輪廓activte該偵聽器將被調用。
但它總是調用。如何解決這個問題?

回答

0

根據文檔@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 

請注意,您可以添加多個以逗號分隔的配置文件名稱。

+0

初始化後,對我來說是晚 – gstackoverflow

+0

** context.getInitParameter( 「spring.profiles.active」)**始終返回null。我啓動應用程序是這樣的:** MVN全新安裝碼頭:運行-Dspring.profiles.active =測試** – gstackoverflow

+0

@gstackoverflow,因爲要得到JVM選項PARAM我們必須應該使用System.getProperty()。代碼已更新。 –