浅析Spring事务失效的情况、原因分析及如何解决:缓存、事务、异步不能在同一个类中相互调用,会失效

  项目中遇到的问题的结论,具体现象就不描述了,通过查资料,就是知道一点就行:缓存、事务、异步不能同一个类中相互调用,会失效(只能在别的类里调用)。具体问题描述我们直接看网上的文章吧。

一、同一个类中方法调用,导致@Transactional失效

一、问题现象

  开发中避免不了会对同一个类里面的方法调用,比如有一个类Test,它的一个方法A,A再调用本类的方法B(不论方法B是用public还是private修饰),但方法A没有声明注解事务,而B方法有。则外部调用方法A之后,方法B的事务是不会起作用的。这也是经常犯错误的一个地方:

 
    @GetMapping("/test")
    private Integer A() throws Exception {
        CityInfoDict cityInfoDict = new CityInfoDict();
        cityInfoDict.setCityName("2");
        /**
         * B 插入字段为 3的数据
         */
        int insert=insertB();
        /**
         * A 插入字段为 2的数据
         */
        int insert = cityInfoDictMapper.insert(cityInfoDict);
 
        return insert;
    }
 
    @Transactional()
    public Integer insertB() throws Exception {
        CityInfoDict cityInfoDict = new CityInfoDict();
        cityInfoDict.setCityName("3");
        cityInfoDict.setParentCityId(3);
 
        return cityInfoDictMapper.insert(cityInfoDict);
    }

二、注解失效原因分析

  其实这还是由于使用Spring AOP代理造成的,因为只有当事务方法被当前类以外的代码调用时,才会由Spring生成的代理对象来管理

三、解决方案

  利用spring提供的动态代理机制。

1、引入spring动态代理:

<!-- aop -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2、方法调用改成动态代理调用:

 
    @GetMapping("/test")
    private Integer A() throws Exception {
        CityInfoDict cityInfoDict = new CityInfoDict();
        cityInfoDict.setCityName("2");
       
       // B 插入字段为 3的数据
        Test test = (Test)AopContext.currentProxy();
 
        int insert=test.insertB();
       
        int insert = cityInfoDictMapper.insert(cityInfoDict);
 
        return insert;
    }
 
    @Transactional()
    public Integer insertB() throws Exception {
        CityInfoDict cityInfoDict = new CityInfoDict();
        cityInfoDict.setCityName("3");
        cityInfoDict.setParentCityId(3);
 
        return cityInfoDictMapper.insert(cityInfoDict);
    }

  可能会提示:Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.

  ze在代理类上添加:@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) 问题解决!!!!!!

以上代码示例见:https://blog.csdn.net/zhangkaixuan456/article/details/109082645

二、Spring事务生效的情况、原理分析及如何解决

一、使用默认的事务处理方式

  因为在java的设计中,它认为不继承RuntimeException的异常是”checkException”或普通异常,如IOException,这些异常在java语法中是要求强制处理的。对于这些普通异常,spring默认它们都已经处理,所以默认不回滚。可以添加rollbackfor=Exception.class来表示所有的Exception都回滚。

二、内部调用

  不带事务的方法调用该类中带事务的方法,不会回滚。因为spring的回滚是用代理模式生成的,如果是一个不带事务的方法调用该类的带事务的方法,直接通过this.xxx()调用,而不生成代理事务,所以事务不起作用。常见解决方法是,拆类。

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

  PROPAGATION_REQUIRED:如果存在一个事务,则支持当前事务。如果没有事务则开启事务;

  PROPAGATION_REQUIRES_NEW:总是开启一个新的事务。如果一个事务已经存在,则将这个存在的事务挂起。

@Service
public class EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;
    public void save(){
        try {        
            this.saveEmployee();  //此处this调用不会开启事务,数据会被保存
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Transactional(propagation = Propagation.PROPAGATION_REQUIRED)
    //此处无论是PROPAGATION_REQUIRED还是PROPAGATION_REQUIRES_NEW,事务均不生效
    public void saveEmployee(){
        Employee employee = new Employee();
        employee.setName("zhangsan");
        employee.setAge("26";
        employeeDao.save(employee);
        throw new RuntimeException();
    }
}

三、问题原因

  原因在于JDK的动态代理,只有被动态代理直接调用时才会产生事务。在SpringIoC容器中返回的调用的对象是代理对象而不是真实的对象,而这里的this是EmployeeService真实对象而不是代理对象。

四、解决办法:

1、方法1、在方法A上开启事务,方法B不用事务或默认事务,并在方法A的catch中throw new RuntimeException();

  在没指定rollbackFor时,默认回滚的异常为RuntimeException,这样使用的就是方法A的事务。(一定要throw new RuntimeException();否则异常被捕捉处理,同样不会回滚。)如下

@Transactional() //开启事务
public void save(){
    try {        
        this.saveEmployee();  //这里this调用会使事务失效,数据会被保存
    }catch (Exception e){
        e.printStackTrace();
        throw new RuntimeException();
    }
}

2、方法2:方法A上不开启事务,方法B上开启事务,并在方法A中将 this 调用改成动态代理调用AopContext.currentProxy(),如下:

public void save(){
    try {        
        EmployeeService proxy =(EmployeeService) AopContext.currentProxy();
        proxy.saveEmployee();
    }catch (Exception e){
        e.printStackTrace();
    }
}

三、至于缓存或异常是同样的问题原因

 

posted @ 2022-03-04 21:28  古兰精  阅读(1823)  评论(0编辑  收藏  举报