spring配置之contextConfigLocation與ContextLoaderListener
阿新 • • 發佈:2019-02-10
最近再次學習spring,不知道是spring版本變化的原因還是時間久了記憶不清晰,覺得以前許多知識點都不同了。
話說好記性不如爛筆頭,於是嘗試寫一寫blog以作記錄。
本篇所寫的spring版本是4.1.4
首先、web程式設計的基礎是servlet,servlet配置的作用是攔截http請求,然後觸發Servlet類或者監聽類。
spring的配置也不例外,它的目的是觸發DispatcherServlet,同時裝載一個XML資原始檔。spring對裝載這個配置檔案有兩種方法。
方法一、
加上init-param,引數為contextConfigLocation,直接告訴spring配置檔案的位置。可以讀入多個配置檔案。
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value >
classpath:config/applicationContext.xml,
classpath:config/base/base.xml,
classpath:config/base/datasource.xml,
classpath:config/base/aop.xml ...
</param-value>
</init-param>
< load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
方法二:
用org.springframework.web.context.ContextLoaderListener,這個是spring的監聽類,它的作用就是載入預設為applicationContext.xml的檔案。並且applicationContext.xml與web.xml位於同目錄。
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>