controller调用多个service方法(不在一个service方法)如何保证事务?

一般controller层调用service的方法我们会将业务写在一个方法里面并加上@Transactional这样就能确保事务:

@Transactional(rollbackFor = Exception.class)
    public void insert() {
       insertMethod1();
       insertMethod2();
    }

如果是下面的写法就会出现insertMethod1()的事务不回滚
Controller层调用:

insertMethod1();
insertMethod2();

Service层:

@Transactional(rollbackFor = Exception.class)
    public void insertMethod1() {
        insertSomething();
    }
@Transactional(rollbackFor = Exception.class)
    public void insertMethod2() {
	    int i=1/0;
	    insertSomething();
    }

这时候执行情况是:insertMethod1()没有回滚
为什么没有全部回滚呢?
因为spring的事务是基于aop实现的,aop的底层又是动态代理,调用 insertMethod1()和insertMethod2()会生成不同的代理对象,所以不能保证一个事务
但是有些时候就是需要我们这么写那该怎么改呢?
利用AopContext.currentProxy(),拿到当前线程的代理对象来请求被调用类的方法,被调用的方法才会被代理
代码如下:

userService.insertMethod1();
((UserService) AopContext.currentProxy()).AopContext.currentProxy().insertMethod2();

你可能感兴趣的:(spring)