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>