今早接手了别人的项目,测试了一下事务,发觉不起作用,检查了N久代码,才发觉是springMVC 配置文件里context:component-scan重复扫码了service,导致事务不起作用(建议MVC scan只扫描action或Controller),下面根据网上的一些资料,整理了一下事务不起作用的几个点:
1、首先使用如下代码 确认你的bean 是代理对象吗?
AopUtils.isAopProxy()
AopUtils.isCglibProxy() //cglib
AopUtils.isJdkDynamicProxy() //jdk动态代理
如果不是 那么就是切入点配置出错了 或者如果你使用了springmvc,可能是context:component-scan重复扫描引起的:
http://jinnianshilongnian.iteye.com/blog/1423971
http://jinnianshilongnian.iteye.com/blog/1762632
http://jinnianshilongnian.iteye.com/blog/1857189
2、如果是aop代理,那么说明代理成功,那么可能是如使用mysql且引擎是MyISAM造成的(因为不支持事务),改成InnoDB即可。
3、 如果你是基于类的代理,而非接口,如果想代理父类里的,可以用
execution(* com.sishuok.es..service..+.(..))
//+表示子类的也扫描(参考http://jinnianshilongnian.iteye.com/blog/1420691)
4、spring事务默认只在发生未被捕获的 RuntimeExcetpion时才回滚,所以,得检查service方法中有没有使用try catch,如果使用了try catch,在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚,或在service层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常(最好不要在service中try catch)
5.针对默认 只在发生未被捕获RuntimeExcetpion时才回滚的情况,可以重设一下exception回滚策略
rollback-for=”java.lang.Exception”
<tx:advice id="tx" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="select*" read-only="true" />
<tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>