SPRING-MVC 啟動重複載入兩次對映
阿新 • • 發佈:2019-01-23
如下web.xml示例:
part1.用spring的配置載入contextConfigLocation
2.配置spring-mvc的contextConfigLocation
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-*.xml </param-value> </context-param> --------------------------------------------------------------------------- <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--查詢controller位置的xml檔案配置 --> <init-param> <param-name>contextConfigLocation</param-name> <!--查詢這裡可以配置多個,用逗號分割或者用萬用字元*也就是第二行 --> <param-value>/WEB-INF/classes/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
非常不幸,part1+2不能互相替代, 並且,如果兩部分的xml重複命中,比如spring-*,就會導致springmvc的對映,scan重複載入兩次。從啟動日誌和啟動時長可以看到。 補充:重複載入還會導致配置的task,schadule任務重複執行!
所以,合理的做法是,把spring-mvc的定義單獨摘出來定義在web容器啟動的時候載入,名稱也換成servlet-mvc.xml避免被spring重複載入, 而在spring的core xml定義中,不要出現mvc的東東
<servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--查詢controller位置的xml檔案配置 --> <init-param> <param-name>contextConfigLocation</param-name> <!--查詢這裡可以配置多個,用逗號分割或者用萬用字元*也就是第二行 --> <param-value>/WEB-INF/classes/servlet-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
<!-- (Annotation方式配置services)enable component scanning (beware that this does not enable mapper scanning!) --> <context:component-scan base-package="com.xx.controller" /> <!-- enable autowire --> <context:annotation-config /> <!-- 預設的註解對映的支援 --> <mvc:annotation-driven /> <!-- 攔截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*/**"/> <bean class="com.xx.interceptors.DebugLogInterceptor" /> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/user/**"/> <mvc:mapping path="/group/**"/> <mvc:mapping path="/groupalbum/**"/> <mvc:mapping path="/message/**"/> <mvc:exclude-mapping path="/user/login"/> <mvc:exclude-mapping path="/user/c/mobile"/> <mvc:exclude-mapping path="/user/c/email"/> <bean class="com.hoomic.interceptors.LoginInterceptor" /> </mvc:interceptor> </mvc:interceptors>