從一個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參數。