2019-10-17 21:31  阅读(1281)
文章分类:Spring boot


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) */
        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回滚呢?代码解决如下:

    } catch (Exception e) {
    return  xxx;


版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> spring源码自定义异常分析