zoukankan      html  css  js  c++  java
  • spring + mybatis 注解 @Transactional失效

    1.问题

    在使用@Transactional注解管理事务的时候会出现很多错误,比如:

    ***  was not registered for synchronization because synchronization is not active
    或者
    Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3ca5cba7]
    JDBC Connection [com.mysql.jdbc.JDBC4Connection@79436e0a] will not be managed by Spring

    总之就是事务没有被spring管理,注解@Transactional失效.

    2.原因:

    重复扫描包的问题. 因为springmvc的配置文件已经扫描了service和controller注解,而spring的配置文件又扫描了一遍,所以会出错. 

    spring 通过 cglib 生成了带有事务功能的代理类.

    但是spring mvc 在扫描一遍又重新生成了 service 层的不带事务功能的代理类,把之前的代理类给覆盖掉了,

    所以会导致事务失效.

    因此解决就是把springmvc扫描service给过滤掉就可以了,

    3.解决:

    让springmvc的配置文件只扫描controller

        <context:component-scan base-package="com.fyq" >
            <context:exclude-filter type="annotation"
                expression="org.springframework.stereotype.Service" />
        </context:component-scan>
        

    通过 filter 把service注解给过滤掉.

    同理 spring 的配置文件只扫描service层,把controller给过滤掉.

        <context:component-scan base-package="com.fyq" >
            <context:exclude-filter type="annotation"
                expression="org.springframework.stereotype.Controller" />
        </context:component-scan>

    该用spring-boot了...

  • 相关阅读:
    第七课 GDB调试 (下)
    设计模式之原型模式
    设计模式之再读重构
    设计模式之代理模式
    设计模式之建造者模式
    设计模式之模板方法模式
    设计模式之抽象工厂模式
    设计模式之工厂模式
    设计模式之单例模式
    设计模式之6大原则
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/10485202.html
Copyright © 2011-2022 走看看