您的位置:首页 > 其它

解决@Transactional事务在类内部方法调用不生效

2018-06-07 14:52 477 查看

  1. 首先描述下类内部方法互相调用,事务不生效的情况UserService测试接口类package cn.sw.study.web.service;/** * Created by shaowei on 2017/4/26. */public interface UserService {    void addInfo();    void addOne();}

  2. UserServiceImpl测试实现类package cn.sw.study.web.service.impl;import cn.sw.study.web.dao.UserMapper;import cn.sw.study.web.model.User;import cn.sw.study.web.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Date;/** * 用户业务类 * Created by shaowei on 2017/4/26. */@Service("userService")public class UserServiceImpl implements UserService{    @Autowired    UserMapper userMapper;    public void addInfo() {        addOne();    }    @Transactional    public void addOne() {        User record = new User();        record.setLoginName("tom");        record.setPwd("111111");        record.setMobile("13913913913");        record.setUsable(1);        record.setCreateTime(new Date());        userMapper.insertSelective(record);        int i = 1/0;    // 测试事物的回滚    }}

  3. addInfo方法上没有事务注解,addOne方法上有事务注解,此时运行addInfo调用addOne方法,不会产生事务,测试数据遇到异常没有回滚。如果从外部类直接调用addOne方法,则事务是可以正常生效的。

  4. 如果想类内部方法调用可以正常使用事务,使用AopContext.currentProxy()来获取代理类再调用

  5. 再次运行,如果没有添加expose-proxy="true"这个属性,则会报错java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.

  6. 在spring配置文件中添加,<aop:aspectj-autoproxy expose-proxy="true"/>,再次运行,则发现事务已经生效,到异常的地方事务正常回滚了

  7. 7

    从日志中也可以看到Creating new transaction和Rolling back JDBC transaction

    END

注意事项

  • 使用 AspectJ 取代 Spring AOP 代理方式也可以解决上面非public和类内部方法调用事务不生效的问题,这里就不做详细说明

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐