@Transactional注解真的有必要声明rollbackFor属性吗?( 二 )


再看getDepth方法,会根据抛出的异常,判断异常名字是否跟我们声明的异常是否相同,相同则返回,不同则递归抛出异常的父类,直到遍历到Throwable.class顶类 。
private int getDepth(Class<?> exceptionClass, int depth) {if (exceptionClass.getName().contains(this.exceptionName)) {// Found it!return depth;}// If we've gone as far as we can go and haven't found it...if (exceptionClass == Throwable.class) {return -1;}return getDepth(exceptionClass.getSuperclass(), depth + 1);}根据二:如果getDepth找不到对应的异常类,就从默认实现类DefaultTransactionAttribute.rollbackOn(Throwalbe x)方法进行判断 。
【@Transactional注解真的有必要声明rollbackFor属性吗?】@Overridepublic boolean rollbackOn(Throwable ex) {return (ex instanceof RuntimeException || ex instanceof Error);}DefaultTransactionAttribute判断抛出的异常是RuntimeException或者Error就会进行回滚 。说明spring没有对非运行时异常(检查时异常)进行处理,这是因为非运行时异常在编码时,是需要我们开发人员手动去进行try catch进行处理的,也不允许抛出非运行时异常,比如IOException,不然编译器编译都不通过,更别谈运行程序了 。
总结:我们规范中要求指定rollbackFor=Exception.class,但是spring中已经包含了RuntimeException的处理,Exception的另一种实现就是非运行时异常,这种我们代码中已经处理了,所以也不需要再去指定 。

经验总结扩展阅读