相信很多人和我一樣配置spring 和 spring mvc項(xiàng)目的台腥,spring的初始化交給ContextLoaderListener進(jìn)行,使用的是applicationContext.xml文件。而spring mvc 初始化是交給DispatcherServlet進(jìn)行的,使用的mvc-context.xml文件
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 加入spring mvc -->
<servlet>
<servlet-name>mvcServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvcServlet</servlet-name>
<url-pattern>/new/*</url-pattern>
</servlet-mapping>
applicationContext.xml
<!-- 使用annotation 自動注冊bean,并保證@Required,@Autowired的屬性被注入 -->
<context:component-scan base-package="org.demo">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
其他配置省略
mvc-context.xml
<!-- 掃描 controller 和 ControllerAdvice類型的 類,其他類型交由spring掃描 -->
<context:component-scan base-package="org.demo">
<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>
其他配置省略...
問題來了
當(dāng)我在界面上測試一個(gè)帶事務(wù)的操作發(fā)現(xiàn)事務(wù)不生效萄焦,我使用的是在service層加入注解事務(wù)@Transactional,開始以為我事務(wù)配置有問題,檢查了很久怎么都沒有發(fā)現(xiàn)有問題拂封。然后我使用junit代碼測試service層發(fā)現(xiàn)事務(wù)是生效的茬射,那么說明了spring mvc的配置造成了事務(wù)不生效。
解決辦法有兩個(gè):
1.指定mvc-context.xml 文件掃描包路徑更為精確點(diǎn)冒签,如果org.demo.controller,但是這樣要確保所有Controller要放在改包下在抛。
mvc-context.xml
2.去掉mvc-context.xml對其他類型注釋的掃描,使用use-default-filters="false"配置
mvc-context.xml
use-default-filters默認(rèn)值為true萧恕,會對@Component, @Repository, @Service,@Controller都進(jìn)行掃描刚梭,我們原意是只對@Controller進(jìn)行掃描的。
use-default-filters說明