spring+springMVC,声明式事务失效,原因以及解决办法

一.声明式事务配置:

    <context:component-scan base-package="com.ada.wuliu"/>
    <context:component-scan base-package="com.wechat"/>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="updateOrderPayBackNotfiy" propagation="REQUIRED"
                isolation="SERIALIZABLE" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>

二.声明式事务失效,原因

根本原因:由子容器扫描装配了@Service 注解的实例。

spring的context是父子容器,由ServletContextListener 加载spring配置文件产生的是父容器,springMVC加载配置文件产生的是子容器,子容器对Controller进行扫描装配时装配了@Service注解的实例 (@Controller 实例依赖@Service实例),而该实例理应由父容器进行初始化以保证事务的增强处理,所以此时得到的将是原样的Service没有经过事务加强处理,故而没有事务处理能力。

三.解决办法

1.修改spring配置文件:

<!-- 不扫描带有@Controller注解的类 ,让 springMVC 子容器加载。 -->
 <context:component-scan base-package="com.ada.wuliu">     
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>     
</context:component-scan>  
原文地址:https://www.cnblogs.com/lmjk/p/7655659.html