spring源码自定义异常分析

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

查了好久,才找到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;

来源:[]()

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » spring源码自定义异常分析

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏