spring學習之ApplicationContext

與BeanFactory通常以編程的方式被創建不同的是,ApplicationContext能以聲明的方式創建,如使用ContextLoader。當然你也可以使用ApplicationContext的實現之一來以編程的方式創建ApplicationContext實例。首先,讓們先分析ContextLoader接口及其實現。

    ContextLoader接口有兩個實現:ContextLoaderListener和ContextLoaderServlet。兩者都實現同樣的功能,但不同的是,ContextLoaderListener不能在與Servlet 2.2兼容的web容器中使用。根據Servlet 2.4規範, servlet context listener要在web應用程序的servlet context建立後立即執行,並要能夠響應第一個請求(在servlet context要關閉時也一樣):這樣一個servlet context listener是初始化Spring ApplicationContext的理想場所。雖然使用哪個完全取決於你,但是在同等條件下應該首選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 above listener
<servlet>
  <servlet-name>context</servlet-name>
  <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
-->

    監聽器首先檢查contextConfigLocation參數,如果它不存在,它將使用/WEB-INF/applicationContext.xml作爲默認值。如果已存在,它將使用分隔符(逗號、冒號或空格)將字符串分解成應用上下文將位置路徑。ContextLoaderServlet同ContextLoaderListener一樣使用'contextConfigLocation'參數。

發佈了58 篇原創文章 · 獲贊 1 · 訪問量 3565
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章