通常使用Spring框架的程序会统一的在Service层运用Spring AOP进行事务控制,分为声明式和编程式两种,互联网上已经有很多的资源介绍Spring事务的配置,Spring Reference也有详细介绍。但是介绍嵌套式事务的并不多。日前本人试图运用AOP记录Service的调用情况并记录到Database,但是发现当Service发生异常时无法正常记录Database log,后来通过为日志服务配置不同的事务策略才解决该问题,本文介绍一下嵌套式事务以及如何为不同的service配置不同的事务策略。
嵌套事务是指AService和BService都配置了事务,但是AService调用了BService的情况。此时BService是用AService的事务呢,还是新开一个自己的事务? Spring配置事务的时候有一个可选的参数propagation,默认为REQUIRED。使用这种策略时BService将使用Aservice的事务。
不管业务逻辑的service是否有异常,Log Service都应该能够记录成功,通常有异常的调用更是用户关心的。Log Service如果沿用业务逻辑Service的事务的话在抛出异常时将没有办法记录日志(事实上是回滚了)。所以希望Log Service能够有独立的事务。日志和普通的服务应该具有不同的策略。先贴上Spring 配置文件transaction.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- configure transaction -->
<tx:advice id="defaultTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
</tx:attributes>
</tx:advice>
<tx:advice id="logTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" propagation="REQUIRES_NEW"
rollback-for="java.lang.Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="defaultOperation"
expression="@within(com.homent.util.DefaultTransaction)" />
<aop:pointcut id="logServiceOperation"
expression="execution(* com.homent.service.LogService.*(..))" />
<aop:advisor advice-ref="defaultTxAdvice" pointcut-ref="defaultOperation" />
<aop:advisor advice-ref="logTxAdvice" pointcut-ref="logServiceOperation" />
</aop:config>
</beans>