java @Transactional 注解类内部调用不回滚问题解决
今天帮同事看一个问题,关于事务在同一个类中,一个方法调用另一个方法 事务不回滚问题,这问题以前也遇到过,不过这次是在springboot项目中来解决,现在直接把方法写出来。
1. POM文件引入 如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency>
2. 在springboot启动类上,添加注解,如下:
package com.szl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.EnableAspectJAutoProxy; @EnableAspectJAutoProxy(exposeProxy = true) @SpringBootApplication public class DemoSzlApplication { public static void main(String[] args) { SpringApplication.run(DemoSzlApplication.class, args); } }
3. 主要实现类,如下:
package com.szl.service.impl; import com.szl.mapper.DemoSzlMapper; import com.szl.mapper.entity.DemoSzl; import com.szl.service.DemoSzlService; import org.springframework.aop.framework.AopContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.beans.Transient; import java.util.Date; @Service("demoSzlService") public class DemoSzlServiceImpl implements DemoSzlService { @Autowired private DemoSzlMapper demoSzlMapper; @Override @Transactional public void saveTest1() { DemoSzl ds1 = new DemoSzl("szl001", new Date()); demoSzlMapper.insert(ds1); try {
// 此处如果方法执行失败,就可以回滚成功。 ((DemoSzlServiceImpl) AopContext.currentProxy()).saveTest2(); } catch (Exception e) { e.printStackTrace(); } } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void saveTest2() { try { DemoSzl ds2 = new DemoSzl("szl002", new Date()); demoSzlMapper.insert(ds2); int t = 1 / 0; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("错误"); } } }
OK, 记录完毕,以上本人亲测已验证。