Spring WebApplicationContext的兩種初始化方式
Spring提供了兩種方式用於初始化WebApplicationContext,ServletContext監聽器、自啟動Servlet。其中只有Servlet2.3以上版本的Web容器才支援ServletContext監聽器方式初始化WebApplicationContext。
一、監聽器方式(org.springframework.web.context.ContextLoaderListener)
1.ContextLoaderListener通過ServletContext上下文引數contextConfigLocation獲取Spring配置檔案的位置,在web.xml檔案中Spring配置檔案的位置,如下
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/beanConfig.xml</param-value>
</context-param>
在這裡可以指定多個檔案,多個檔案之間用逗號或空格分割,也可以指定帶資源型別字首的路徑配置,如“calsspath:/applicationContext.xml”、“classpath*:applicationContext*.xml”,對於未帶資源型別字首的路徑配置預設其路徑相對於Web部署的根路徑。
classpath與classpath*的區別:假設有多個jar包或類路徑下有一個相同的包名如(com.test),classpath只會在第一個載入的com.test包下查詢,而classpath*會在所有jar包和類路徑下查詢。
2.在web.xml檔案中配置監聽器ContextLoaderListener,如下
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
<listener>
二、自啟動Servlet方式(org.springframework.web.context.ContextLoaderServlet)
1.ContextLoaderServlet同樣通過ServletContext上下文引數contextConfigLocation獲取Spring配置檔案的位置,配置跟一樣。
2.配置自啟動ContextLoaderServlet,如下
<servlet>
<servlet-name>springContextLoaderServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>