2014-03-19 36 views
1

我需要在檢查一些參數後修改我的項目中的web.xml。我的contextConfigLocation在web.xml參數如下:如何有條件地將ContextConfigLocation添加(或修改)到web.xml?

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value> 
    classpath:*/test-spring-config.xml classpath:*/someContext.xml classpath:applicationContext.xml classpath:databaseContext.xml</param-value> 
</context-param> 

現在我需要添加類路徑:在web.xml中在檢查一些條件securityContext.xml的contextConfigLocation之前我的應用程序加載在tomcat。 我已經在我的applicationInitializer類,它實現了ServletContextListener如下試着這樣做(部分代碼所示):

public class ApplicationInitializer implements ServletContextListener 
{ 
    public void contextInitialized(ServletContextEvent event) 
{ ServletContext sc = event.getServletContext(); 
     if(someConditionIsTrue){ 
     XmlWebApplicationContext appContext = new XmlWebApplicationContext(); 
     appContext.setConfigLocation("classpath:securityContext.xml"); 
     appContext.setServletContext(sc); 
     appContext.refresh(); 
     sc.setAttribute("org.springframework.web.context.WebApplicationContext.ROOT",appContext); 
} 

但是這是行不通的,因爲我再次加載的背景下,我的web.xml爲

<listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

有人可以建議如何處理這個問題?任何建議表示讚賞。

回答

3

ApplicationInitializer應該爲您的方案,並監聽器類應指向ApplicationInitializer在web.xml

1

後鬥爭了幾天延長的ContextLoaderListener,我能夠通過創建一個CustomContextLoaderListener類延伸做到這一點的ContextLoaderListener並覆蓋其createContextLoader方法現在返回customContextLoader如下:

@Override 
protected ContextLoader createContextLoader(){ 
return new CustomContextLoader(); 
} 

CustomContextLoader類擴展的ContextLoader,我已經覆蓋其customizeContext方法如下:

@Override 
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext){ 
super.customizeContext(servletContext, applicationContext); 
String[] oldLocations = applicationContext.getConfigLocations(); 
String[] newLocations; 
if(conditionIsTrue){ 
newLocations = new String[oldLocations.length+1]; 
for (int i = 0; i < oldLocations.length; i++) { 
     newLocations[i] = oldLocations[i]; 
    } 
newLocations[oldLocations.length] ="classpath:securityContext.xml"; 
}else{ 
    newLocations = new String[oldLocations.length]; 
    newLocations = Arrays.copyOf(oldLocations, oldLocations.length); 
} 
applicationContext.setConfigLocations(newLocations); 
} 

不要忘記添加customContextLoaderListener類在web.xml。

<listener> 
<listener-class>com.abc.px.customContextLoaderListener</listener-class> 
</listener> 

這就是它!這樣我可以有條件地在web.xml中設置我的上下文。希望這可以幫助別人!

+0

我相信這就是我在我的答案中提到的;) – Prasad

+0

是啊!我從你的答案中挖掘了以上所有內容。謝了哥們! – abhilash

相關問題