web spring 容器
使用spring的web應用時,不用手動創建spring容器,而是通過配置文件聲明式地創建spring容器,因此,在web應用中創建spring容器有如下兩種方式:
一.直接在web.xml文件中配置spring容器
二.利用第三方MVC框架的擴展點,創建spring容器
其實第一種方式最為常見。
為了讓spring容器隨web的應用的啟動而自動啟動,有如下兩種方法
??? 1.利用ServletContextListener實現
??? 2.采用load-on-startup Servlet實現
?
對于利用ServletContextListener實現方式,操作及說明如下
??? spring提供ServletContextListener的一個實現類ContextLoadListener,該類可以作為Listener使用,會在創建時自動查找web-inf/applicationContext.xml文件,因此,如果只有一個配置文件,并且名為applicationContext.xml,只需要在web.xml文件中加入如下配置即可
如果有多個配置文件需要載入,則考慮用<context-param>元素來確定配置文件的文件名。ContextLoadListenter加載時,會查找名為contextConfigLocation的參數。因此,配置context-param時,參數名應該是contextConfigLocation
?
帶多個配置文件的web.xml文件如下
[html]?view plaincopyprint?
如是沒有通過contextConfigLocation指定配置文件,spring會自動查找applicationContext.xml文件;如果有contextConfigLocation,則利用該參數確定的配置文件,如果無法找到合適的配置文件,spring將無法正常初始化
??? spring根據bean定義創建WebApplicationContext對象,并將其保存在web應用的ServletContext中。大部分情況下,應用的Bean無須感受到ApplicationContext的存在,只要利用ApplicationContext的IOC容器
如果需要在應用中獲取ApplicationContext實例,可以通過如下代碼獲取
//獲取當前web應用的spring的容器
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletContext);
二.利用第三方MVC框架的擴展點,創建spring容器
????? Struts有一個擴展點PlugIn,spring正是利用了PlugIn這個擴展點,從而提供了與Struts的整合。。spring提供了PlugIn的實現類org.springframework.web.struts.ContextLoadPlugIn,這個實現類可作為struts的PlugIn配置,Struts框架啟動時,將自動創建Spring容器
???? 為了利用struts的PlugIn創建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屬性值時,即可以指定一個spring配置文件的位置,可以指定多個spring配置文件的位置
總結
以上是生活随笔為你收集整理的web spring 容器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Twitter Snowflake算法详
- 下一篇: IDL 字符串