SSH答疑解惑系列(一)——spring容器是如何啟動的_spring

來源:互聯網
上載者:User

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容器啟動後,自動讀取並載入相應的設定檔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.