SSH架構十分受歡迎,其中有一個原因就是spring可以和Struts2架構無縫整合。在使用spring時,無需手動建立web容器,而是通過設定檔聲明式建立spring容器。
在web應用中,建立spring容器有兩種方式: 在web.xml中配置 利用第三方MVC架構建立
第一種比較常用,第二種方法只對特定架構有效,在此就不做介紹,下面只介紹第一種方法。
為了讓Spring容器隨Tomcat/JBoss等啟動而自動啟動,我們用到了ServletContextListener監聽器來完成。
先來看下在項目的web.xml中,整合spring的配置。
<!-- 整合spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param>
上述配置中,
1、在ContextLoaderListener中,ContextLoaderListener監聽器實現了ServletContextListener介面。他在建立時自動尋找WEB/INF下的applicationContext.xml檔案。
2、當需要匯入的設定檔有多個時需要使context-param標籤,來確定設定檔的檔案名稱。通過尋找contextConfigLocation的初始化參數。
public void contextInitialized(ServletContextEvent event) { //1、載入spring的web容器 this.contextLoader = createContextLoader(); //2、初始化spring的web容器並載入設定檔。 this.contextLoader.initWebApplicationContext(event.getServletContext()); }建立spring容器的大致流程: /** * 建立 ContextLoader. Can be overridden in subclasses. * @return the new ContextLoader */ protected ContextLoader createContextLoader() { return new ContextLoader(); }
小結:
ssh架構中,我們通過配置就可以實現spring容器隨著Tomcat/Jboss等的啟動而自動啟動,而無需我們手動開啟。這是通過監聽器來實現的,當spring容器啟動後,自動讀取並載入相應的設定檔。