web spring 容器
使用spring的web應(yīng)用時(shí),不用手動(dòng)創(chuàng)建spring容器,而是通過(guò)配置文件聲明式地創(chuàng)建spring容器,因此,在web應(yīng)用中創(chuàng)建spring容器有如下兩種方式:
一.直接在web.xml文件中配置spring容器
二.利用第三方MVC框架的擴(kuò)展點(diǎn),創(chuàng)建spring容器
其實(shí)第一種方式最為常見(jiàn)。
為了讓spring容器隨web的應(yīng)用的啟動(dòng)而自動(dòng)啟動(dòng),有如下兩種方法
??? 1.利用ServletContextListener實(shí)現(xiàn)
??? 2.采用load-on-startup Servlet實(shí)現(xiàn)
?
對(duì)于利用ServletContextListener實(shí)現(xiàn)方式,操作及說(shuō)明如下
??? spring提供ServletContextListener的一個(gè)實(shí)現(xiàn)類(lèi)ContextLoadListener,該類(lèi)可以作為L(zhǎng)istener使用,會(huì)在創(chuàng)建時(shí)自動(dòng)查找web-inf/applicationContext.xml文件,因此,如果只有一個(gè)配置文件,并且名為applicationContext.xml,只需要在web.xml文件中加入如下配置即可
如果有多個(gè)配置文件需要載入,則考慮用<context-param>元素來(lái)確定配置文件的文件名。ContextLoadListenter加載時(shí),會(huì)查找名為contextConfigLocation的參數(shù)。因此,配置context-param時(shí),參數(shù)名應(yīng)該是contextConfigLocation
?
帶多個(gè)配置文件的web.xml文件如下
[html]?view plaincopyprint?
如是沒(méi)有通過(guò)contextConfigLocation指定配置文件,spring會(huì)自動(dòng)查找applicationContext.xml文件;如果有contextConfigLocation,則利用該參數(shù)確定的配置文件,如果無(wú)法找到合適的配置文件,spring將無(wú)法正常初始化
??? spring根據(jù)bean定義創(chuàng)建WebApplicationContext對(duì)象,并將其保存在web應(yīng)用的ServletContext中。大部分情況下,應(yīng)用的Bean無(wú)須感受到ApplicationContext的存在,只要利用ApplicationContext的IOC容器
如果需要在應(yīng)用中獲取ApplicationContext實(shí)例,可以通過(guò)如下代碼獲取
//獲取當(dāng)前web應(yīng)用的spring的容器
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletContext);
二.利用第三方MVC框架的擴(kuò)展點(diǎn),創(chuàng)建spring容器
????? Struts有一個(gè)擴(kuò)展點(diǎn)PlugIn,spring正是利用了PlugIn這個(gè)擴(kuò)展點(diǎn),從而提供了與Struts的整合。。spring提供了PlugIn的實(shí)現(xiàn)類(lèi)org.springframework.web.struts.ContextLoadPlugIn,這個(gè)實(shí)現(xiàn)類(lèi)可作為struts的PlugIn配置,Struts框架啟動(dòng)時(shí),將自動(dòng)創(chuàng)建Spring容器
???? 為了利用struts的PlugIn創(chuàng)建Spring容器,只需要在struts配置文件struts-config.xml中增加如下片段即可
?<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
?? <set-property property="contextConfigLocation" value="/WEB-INF/actionContext.xml,/WEB-INF/appContext.xml,/WEB-INF/daoContext.xml" />
?</plug-in>
????? 其中,指定contextConfigLocation屬性值時(shí),即可以指定一個(gè)spring配置文件的位置,可以指定多個(gè)spring配置文件的位置
總結(jié)
以上是生活随笔為你收集整理的web spring 容器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Twitter Snowflake算法详
- 下一篇: IDL 字符串