MyBatis和SpringMVC集成事务在Junit测试下有效但是在实际项目无效的问题

一、问题说明

项目框架采用SSM,集成了事务回滚(方式见下),在单元测试的时候,测试事务是有效的,但是在实际项目上线的时候,却没有效果。

二、集成方式

application-mybatis.xml(以下xml屏蔽了一些无关的细节)

    <!-- 数据连接池 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver.dev}"></property>
        <property name="url" value="${jdbc.url.dev}"></property>
        <property name="username" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!-- 事务配置1:需手动注解 -->
    <!-- proxy-traget-class true对类进行代理,如果是false表示对接口进行代理,使用时需要在类或者方法上加上 @Transactional 注解。 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

application-common.xml  (关键是让Spring管理排除Controller部分)

    <!-- 会自动扫描com.mc.bsframe下的所有包,包括子包下除了@Controller的类。 -->
    <scpan:component-scan base-package="com.mc.bsframe">
        <scpan:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <scpan:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </scpan:component-scan>

spring-mvc.xml (关键是只处理Controller部分)

    <!-- 只扫描base-package下的用Controller注解的类。 -->
    <context:component-scan base-package="com.mc.bsframe.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <!-- 必须要包括ControllerAdvice才能处理全局异常。 -->
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

基本关于事务的配置如上,但是我发现,偶尔会有失效的情况,

三、分析

为什么Junit4测试下有效,猜测因为Junit4下创建的是一个上下文对象,而实际项目是一个Spring上下文,一个SpringMVC上下文?

四、解决方法

在spring-mvc.xml中添加排除扫描Service的配置,以前语句仅仅是包含了Controller和ControllerAdvice,如下:

    <!-- 只扫描base-package下的用Controller注解的类。 -->
    <context:component-scan base-package="com.mc.bsframe.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <!-- 必须要包括ControllerAdvice才能处理全局异常。 -->
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
        <!-- !!!最好加上这句让SpringMVC管理的时候排除Service层,避免事务失效的问题。 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>
原文地址:https://www.cnblogs.com/LiuChunfu/p/5859101.html