1. 在struts-config.xml里,以插件的形式

xml 代碼
  1. < plug-in className="org.springframework.web.struts.ContextLoaderPlugIn" / >  
  2.     < set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" / >  
  3. < / plug-in >   

這種方式如果沒(méi)有配置contextConfigLocation的值,則會(huì)自動(dòng)加載xx-servlet.xml.

xx的值是和web.xml里的配置org.apache.struts.action.ActionServlet的servlet-name的值一樣

如下:xx的值也就是 action,所以會(huì)自動(dòng)加載action-servlet.xml

xml 代碼
  1. < servlet >  
  2.     < servlet-name >action< / servlet-name >  
  3.     < servlet-class >org.apache.struts.action.ActionServlet< / servlet-class >  
  4.     < load-on-startup >1< / load-on-startup >  
  5.   < / servlet >  
  6.   < servlet-mapping >  
  7.     < servlet-name >action< / servlet-name >  
  8.     < url-pattern >*.do< / url-pattern >  
  9.   < / servlet-mapping >  

 如果sturts-config.xml里配置了contextConfigLocation的值,那么就不會(huì)自動(dòng)加載xx-servlet.xml了,而只會(huì)加載contextConfigLocation所指定的xml.

 2. 第2種方式

在web.xml里配置Listener

xml 代碼
  1. <listener>  
  2.         <  listener-class>org.springframework.web.context.ContextLoaderListener<listener-class>  
  3.     <  /  listener>  

 

如果在web.xml里給該Listener指定要加載的xml,如:

xml 代碼
  1. <context-param>  
  2.         <param-name>contextConfigLocationparam-name>  
  3.         <param-value>classpath*:spring/*.xmlparam-value>  
  4.     context-param>  

則會(huì)去加載相應(yīng)的xml,而不會(huì)去加載/WEB-INF/下的applicationContext.xml。。但是,如果沒(méi)有指定的話,默認(rèn)會(huì)去/WEB-INF/下加載applicationContext.xml。

 

3. 第三種方式:ContextLoaderServlet

xml 代碼
  1. < servlet>    
  2.         < servlet-name>context< / servlet-name>    
  3.         < servlet-class>org.springframework.web.context.ContextLoaderServlet< / servlet-class>    
  4.         < load-on-startup>1< / load-on-startup>    
  5.     < / servlet>  

 

 這種方式和第二種Listener方式一樣,唯一的區(qū)別就是用Listener方式初始化ApplicationContext,可以和用第一種方式(struts-config.xml里 plugin方式)同時(shí)存在,而ContextLoaderServlet則不可以和第一種方式同時(shí)存在

總結(jié):

ContextLoaderServlet已經(jīng)不推薦用了,它只是為了兼容低版本的servlet.jar才用的。

總的來(lái)說(shuō):Listerner要比Servlet更好一些,而且Listerner監(jiān)聽(tīng)?wèi)?yīng)用的啟動(dòng)和結(jié)束,而Servlet啟動(dòng)要稍微延遲一些。
用以下方法取得ApplicationContext:
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());



久久不醉