Spring异常捕获而且回滚事务的方法

默认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>

 
————————————————
版权声明:本文为CSDN博主「学习园」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010644448/article/details/15812267

原文地址:https://www.cnblogs.com/dogdogwang/p/13019036.html