排查spring事务不生效

相信很多人和我一样配置spring 和 spring mvc项目的,spring的初始化交给ContextLoaderListener进行,使用的是applicationContext.xml文件。而spring mvc 初始化是交给DispatcherServlet进行的,使用的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>

其他配置省略...

问题来了
当我在界面上测试一个带事务的操作发现事务不生效,我使用的是在service层加入注解事务@Transactional,开始以为我事务配置有问题,检查了很久怎么都没有发现有问题。然后我使用junit代码测试service层发现事务是生效的,那么说明了spring mvc的配置造成了事务不生效。

解决办法有两个:

1.指定mvc-context.xml 文件扫描包路径更为精确点,如果org.demo.controller,但是这样要确保所有Controller要放在改包下。

mvc-context.xml

2.去掉mvc-context.xml对其他类型注释的扫描,使用use-default-filters="false"配置

mvc-context.xml

use-default-filters默认值为true,会对@Component, @Repository, @Service,@Controller都进行扫描,我们原意是只对@Controller进行扫描的。

use-default-filters说明
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容