SpringMVC依赖于Spring,但是利用SpringIOC配置其他bean的时候回被初始化两次
web.xml同时配置SpringMVC Servlet过滤和Spring的过滤器
<!-- spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:bean.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- SpringMVC配置 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
这样实体会被初始化两次,解决办法:SpringMVC配置与Spring配置过滤掉扫描的注解
SpringMVC配置
<context:component-scan base-package="cn.liangqinghai" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
其中use-default-filters="false"尤为重要,忽略掉缺省的过滤器
Spring配置
<context:component-scan base-package="cn.liangqinghai"> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>