spring源码自定义异常分析
2018-02-04 20:32
447 查看
查了好久,才找到spring事务对自定义异常的分析和应用,看类RuleBasedTransactionAttribute,该类的简介如下:
spring对指定异常的回滚在于 rollbackOn 方法,该类默认的实现是在DefaultTransactionAttribute类中,而RuleBasedTransactionAttribute重写了该方法,简化后代码如下:
另外,如果我们需要在事务控制的service层类中使用try catch 去捕获异常后,会使事务回滚机制失效,因为该类的异常并没有抛出,即不触发事务管理机制。怎样才能既用try catch去捕获异常,又让出现异常后spring回滚呢?代码解决如下:
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;
相关文章推荐
- Dubbo源码分析(三):自定义Schema--基于Spring可扩展Schema提供自定义配置支持(spring配置文件中 配置标签支持)
- 【spring源码分析】BeanDefinitionRegistryPostProcessor接口可自定义bean加入IOC
- spring+mybatis启动NoClassDefFoundError异常分析三部曲之三:改spring源码,取详细错误
- 分析Spring 源码前需要了解的java自定义注解
- Spring IOC源码分析-自定义标签加载
- 源码分析Elastic-Job前置篇:Spring自定义命名空间原理
- Spring EmptyResultDataAccessException异常的源码分析和解决方法
- Hadoop2.7.3 mapreduce(二)类型匹配异常解决方案及源码分析
- Spring Aop源码分析
- Spring boot源码分析-yaml语言(9)
- spring 源码分析--第二章 AbstractBeanFactory
- Spring编程式事务与声明式事务源码分析
- Spring 源码分析(四) ——MVC(五)初始化阶段
- Spring源码分析----AOP通知以及编程式AOP
- 【Spring】DispatcherServlet源码分析
- springboot源码分析14-ApplicationContextInitializer原理Springboot中PropertySource注解多环境支持以及原理
- spring源码分析(1)——AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner的初始化
- Spring Core Container 源码分析七:注册 Bean Definitions
- JUnit源码分析 - 扩展 - 自定义Rule