Spring的事务回滚

在JavaEE的开发中,我们通常会将Spring的事务边界定在Service层上,范例如下(开发的都知道,举例而已):
<aop:config proxy-target-class="true">
	<aop:pointcut id="serviceMethod" expression=" execution(* me.lb.service..*(..))" />
	<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<!-- 粗略的都加了,具体看实际要求 -->
		<tx:method name="*" />
	</tx:attributes>
</tx:advice>

但是,这样配置的话,对于Service直接调用Dao是没有问题的(Dao出错都属于Unchecked Exceptions),我们并没有考虑到Service调用Service的情况(Service出错的情况较多),那实际又是怎么样,事务会如何处理,我们可以通过代码、搜集资料,可以知道:Spring的事务处理默认地只在抛出Unchecked Exceptions时才标识事务回滚,但抛出的Checked Exceptions将不会进行事务回滚。我们可以通过以下代码验证:
范例1:(不进行回滚)
public void delete(User user) throws Exception {
	userDao.delete(user);
	throw new Exception();
}

范例2:(进行回滚)
public void delete(User user) throws Exception {
	userDao.delete(user);
	throw new RuntimeException();
}

这样的话,当Service层相互调用时,如果我们抛出的不是Unchecked Exceptions,则会错误的进行回滚,这并不是我们想看到的,所以我们只需要设置ollback-for即可:
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<tx:method name="*" rollback-for="Exception" />
	</tx:attributes>
</tx:advice>

这样配置,上述的范例1也可以正常的回滚了。

附注:
Unchecked Exceptions:Error和RuntimeException及其子类;
Checked Exceptions:除Unchecked Exceptions之外的所有异常。

你可能感兴趣的:(spring)