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 class='org.springframework.orm.hibernate3.HibernateTransactionManager'> <property name='sessionFactory' ref='sessionFactory' /></bean><tx:advice 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 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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
