您的位置:首页 > 编程语言 > Java开发

Mybatis+SpringMVC+注解事务遇到的一些问题及解决

2015-12-07 14:37 711 查看

这两天要搭建一个小型购物网站的后台系统框架(Mybatis+SpringMVC+mysql),我使用的是注解事务,遇到了一些问题:

1.事务不起作用;

2.在业务逻辑层使用注解事务时出错;

查看Spring官方文档和上网找了一些资料,解决了问题,我总结了一下,要注意一下的地方:

第一个问题:事务不起作用

我使用的是SpringMVC,所以最主要的问题,在SpringConfig.xml和SpringMVC.xml这两个文件中!我们把service的扫描放到SpringConfig.xml中,把controller的扫描放到SpringMVC.xml中!

SpringConfig.xml配置文件


<!-- 扫描业务组件,除了@Controller -->

<context:component-scan base-package="com.shopweb">

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />

</context:component-scan>

SpringMVC.xml配置文件



<!-- 只用来扫描controller ,use-default-filters设置成false才能让注解事务起作用-->

<context:component-scan base-package="com.shopweb.web.controller" use-default-filters="false">

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />

</context:component-scan>

第二个问题:在业务逻辑层使用注解事务时出错

首先看我的配置文件

<!-- 启动spring注解 -->

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" />

我想明白的人,一定会看到其中的关键就是proxy-target-class="false"这个属性

下面来解释一下这个属性:

proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。一句直白的话,就是true是需要在类中使用事务,false或者不设置就是在接口中使用事务

这个问题要感谢这篇帖子,大家可以去看看原版帖子!

大家如果遇到这些问题,对照着修改一下就基本能解决问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: