spring源码自定义异常分析

查了好久,才找到spring事务对自定义异常的分析和应用,看类RuleBasedTransactionAttribute,该类的简介如下:

TransactionAttribute implementation that works out whether a given exception should cause transaction rollback by applying a number of rollback rules, both positive and negative. If no rules are relevant to the exception, it behaves like DefaultTransactionAttribute (rolling back on runtime exceptions).

spring对指定异常的回滚在于 rollbackOn 方法,该类默认的实现是在DefaultTransactionAttribute类中,而RuleBasedTransactionAttribute重写了该方法,简化后代码如下:

    /** * Winning rule is the shallowest rule (that is, the closest in the * inheritance hierarchy to the exception). If no rule applies (-1), * return false. * @see TransactionAttribute#rollbackOn(java.lang.Throwable) */
    @Override
    public boolean rollbackOn(Throwable ex) {
        RollbackRuleAttribute winner = null;
        int deepest = Integer.MAX_VALUE;

      // 查找匹配异常
        if (this.rollbackRules != null) {
            for (RollbackRuleAttribute rule : this.rollbackRules) {
                int depth = rule.getDepth(ex);
                if (depth >= 0 && depth < deepest) {
                    deepest = depth;
                    winner = rule;
                }
            }
        }

        // User superclass behavior (rollback on unchecked) if no rule matches.
        if (winner == null) {
            logger.trace("No relevant rollback rule found: applying default rules");
            return super.rollbackOn(ex);
        }

        return !(winner instanceof NoRollbackRuleAttribute);
    }

另外,如果我们需要在事务控制的service层类中使用try catch 去捕获异常后,会使事务回滚机制失效,因为该类的异常并没有抛出,即不触发事务管理机制。怎样才能既用try catch去捕获异常,又让出现异常后spring回滚呢?代码解决如下:

//假设这是一个service类的片段
try{ 
     //出现异常
} catch (Exception e) {
     e.printStackTrace();
     //设置手动回滚(重点!!!!!!)
     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
 }
//此时return语句能够执行
return  xxx;
    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/zhuqiuhui/article/details/79254709
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞