Spring异常捕获且回滚事务解决方案
作者:学习园 时间:2023-04-25 18:32:41
默认spring只在发生未被捕获的runtimeexcetpion时才回滚。
最笨的办法:代码级控制:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
为何在aop advitor中配置rollba-for=“java.lang.Exception”异常时不回滚呢?
问题已解决:
原理:spring aop 异常捕获原理:被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认情况下aop只捕获runtimeexception的异常,但可以通过
<tx:method name="upd*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
配置来捕获特定的异常并回滚
换句话说在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚
解决方案:
方案1.例如service层处理事务,那么service中的方法中不做异常捕获,或者在catch语句中最后增加throw new RuntimeException()语句,以便让aop捕获异常再去回滚,并且在service上层(webservice客户端,view层action)要继续捕获这个异常并处理
方案2.在service层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常(现在项目的做法)
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="upd*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="canyin" expression="execution(* com.laphone.base.baseservice.*.*(..)) ||execution(* com.laphone.canyin.*.service.*.*(..)) || execution(* com.laphone.canyin.*.*.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="canyin" />
</aop:config>
来源:https://blog.csdn.net/u010644448/article/details/15812267
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
C# 无边框窗体之窗体移动实现代码
Java实现输出数字三角形实例代码
![](https://img.aspxhome.com/file/2023/4/58304_0s.png)
C#实现把彩色图片灰度化代码分享
避免sql注入_动力节点Java学院整理
android开发教程之自定义属性用法详解
SpringBoot集成Elasticsearch过程实例
![](https://img.aspxhome.com/file/2023/6/70486_0s.png)
SpringBoot线程池和Java线程池的使用和实现原理解析
unity5.6 导出gradle工程 Android Studio 导入问题及处理方法
![](https://img.aspxhome.com/file/2023/8/138348_0s.png)
Java使用JDBC或MyBatis框架向Oracle中插入XMLType数据
Java面试之动态规划与组合数
![](https://img.aspxhome.com/file/2023/2/60152_0s.png)
Java生成10个1000以内的随机数并用消息框显示数组内容然后求和输出
![](https://img.aspxhome.com/file/2023/1/79221_0s.png)
java面试try-with-resources问题解答
![](https://img.aspxhome.com/file/2023/9/78949_0s.png)
C#/VB.NET 实现彩色PDF转为灰度PDF
![](https://img.aspxhome.com/file/2023/9/92889_0s.jpg)
Android使用DrawerLayout实现双向侧滑菜单
![](https://img.aspxhome.com/file/2023/4/138394_0s.gif)
Spring实战之协调作用域不同步的Bean操作示例
Android App中实现简单的刮刮卡抽奖效果的实例详解
![](https://img.aspxhome.com/file/2023/3/138903_0s.gif)