applicationContext.xml是隨ContextLoaderListener的加載而執行的,web
<!-- Spring --> <!-- 配置Spring配置文件路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <!-- 配置Spring上下文監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring -->
而xxx-servlet.xml是隨DispatcherServlet的加載而執行的,spring
<!-- Spring MVC 核心控制器 DispatcherServlet 配置 --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <!-- 攔截全部/rest/* 的請求,交給DispatcherServlet處理,性能最好 --> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
在web.xml中,加載順序是listener>filter>servlet,因此applicationContext.xml先加載!spring-mvc
首先ContextLoaderListener加載核心的spring.xml,以及數據源和事務管理等配置文件spring-batis.xmlmybatis
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
而後DispatcherServlet加載spring-mvc.xmlmvc
<servlet> <description>spring-mvc</description> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-mvc.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>