spring中使用this调用事务失效的原因

  • spring中使用this调用事务失效的原因

spring中在一个拥有事务的方法A中调用另一个会挂起事务并创建新事务的方法B,如果使用this调用这个方法B,
此时方法B抛出了一个一场,此时的方法B的事务会失效的。并不会回滚。
如下:

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:Application-spring.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTest extends AbstractJUnit4SpringContextTests {
}
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class TaskServiceImpl extends SpringTest {

    @Autowired
    public TaskService taskService ;

    @Test
    public void testPing() {
        taskService. test1();
    }

}
@Service
public class TaskService {

    @Autowired
    private TaskManageDAO taskManageDAO;

    @Transactional
    public void test1(){
        try {        
            this.test2();//这里调用会使事务失效,两条数据都会被保存
            /*           
            原因是:JDK的动态代理。
            在SpringIoC容器中返回的调用的对象是代理对象而不是真实的对象
            只有被动态代理直接调用的才会产生事务。
            这里的this是(TaskService)真实对象而不是代理对象
             */
             //解决方法
            TaskService proxy =(TaskService) AopContext.currentProxy();
            proxy.test2();
        }catch (Exception e){
            e.printStackTrace();
        }
        Task task = new Task();
        task.setCompleteBy("wjl练习1");
        task.setCompleteTime(new Date());
        taskManageDAO.save(task);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    // 这个事务的意思是如果前面方法有事务存在,会将前面事务挂起,再重启一个新事务
    public void test2(){
        Task task = new Task();
        task.setCompleteBy("wjl练习2");
        task.setCompleteTime(new Date());
        taskManageDAO.save(task);
        throw new RuntimeException();
    }
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值