spring mvc事务没有生效的原因
spring-mvc事務配置如下
?
<tx:advice id="transactionAdvice" transaction-manager="transactionManager"><tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="withdrawals" propagation="REQUIRED" /> <tx:method name="pay" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="select*" propagation="SUPPORTS" /><tx:method name="*" rollback-for="Exception" /> </tx:attributes> </tx:advice><aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.*.service.impl.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /></aop:config>?
但在service允許代碼報錯后,事務回滾不生效
根據 百度上的一些情況也總結了幾種
第一種:在針對事務的類中拋出RuntimeException異常,而不是拋出Exception。
第二種: 不能在方法中使用try catch拋出異常,不然不會回滾
第三種:
?
第4種:上面3種使用后都沒有效果,百度到第4種方式
?
將在spring-mvc.xml下的
?
<context:component-scan base-package="com.aa.*" >
</context:component-scan>
改成
<context:component-scan base-package="com.aa.*" >
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
進行掃描 既可。
原因是:如果使用了spring+mvc,則context:component-scan重復掃描問題可能會引起事務失敗,因為
spring的子容器先于父容器啟動,造成在controller中注入service時還沒有加載事務;
有2種配置方法防止重復掃描:
?
1 在主容器中(applicationContext.xml),將Controller的注解排除掉:
?
<context:component-scan base-package="com"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
?2 或者在springMVC配置文件中將Service注解排除掉 :
?
?
<context:component-scan base-package="com"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>?
?
?
因為spring的context是父子容器,所以會產生沖突,Controller會首先被掃描裝配,而此時的Service還沒有進行事務的加強處理(AOP),獲得的將是原樣的Service(沒有經過事務加強處理,故而沒有事務處理功能) ,最后才是applicationContext.xml中的掃描進行事務處理。
?
總結
以上是生活随笔為你收集整理的spring mvc事务没有生效的原因的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot常用配置简介
- 下一篇: spring和springMVC的面试问