從一個web應用建立ApplicationContext

來源:互聯網
上載者:User
從一個web應用建立ApplicationContext

與BeanFactory總是以編程的方式建立相反,ApplicationContext可以通過使用比如ContextLoader聲明式地被建立。當然你也可以用ApplicationContext的任一種實現來以編程的方式建立它。首先,我們來看看ContextLoader以及它的實現。

ContextLoader有兩個實現:ContextLoaderListener和ContextLoaderServlet。它們兩個有著同樣的功能,除了listener不能在Servlet 2.2相容的容器中使用。自從Servelt 2.4規範,listener被要求在web應用啟動後初始化。很多2.3相容的容器已經實現了這個特性。使用哪一個取決於你自己,但是如果所有的條件都一樣,你大概會更喜歡ContextLoaderListener;關於相容方面的更多資訊可以參照ContextLoaderServlet的JavaDoc。

你可以象下面這樣用ContextLoaderListener註冊一個ApplicationContext:

<context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value></context-param><listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- OR USE THE CONTEXTLOADERSERVLET INSTEAD OF THE LISTENER<servlet>    <servlet-name>context</servlet-name>    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>    <load-on-startup>1</load-on-startup></servlet>-->

這個listener需要檢查contextConfigLocation參數。如果不存在的話,它將預設使用/WEB-INF/applicationContext.xml。如果它存在,它就會用預先定義的分隔字元(逗號,分號和空格)分開分割字串,並將這些值作為應用上下文將要搜尋的位置。ContextLoaderServlet可以用來替換ContextLoaderListener。這個servlet像listener那樣使用contextConfigLocation參數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.