A-A+
AOP的事务包裹
我们有时候会希望这样:
- @拦截的注解
- private void 我是被拦截的函数() {
- ... ....
- }
- //环绕通知
- @Around("...")
- public void roundRun(ProceedingJoinPoint joinPoint) {
- try {
- //执行被拦截的函数
- joinPoint.proceed();
- //做一些记录或者业务逻辑判断
- ... ...
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
在“做一些记录或者业务逻辑判断”发生异常时,有时候我们希望之前被拦截的函数也能够进行事务回滚,但是最终再测试的时候却发现并没有按照我们预想的那样进行回滚,这时候我们需要这样做:
1. 设置事务的拦截排序号为n。
- <!-- 配置事务管理 -->
- <tx:annotation-driven transaction-manager="txManager"
- proxy-target-class="true" order="n"/>
2. 设置自定义的拦截排序号为n+1。
- /**
- * 测试用AOP拦截,被事务包裹
- */
- @Aspect
- @Order(n+1)
- @Component
- public class 我是AOP实现类 {
- ... ...
- }
之所以这样做,是因为:
1. 如果事务拦截的排序号低。
- 事务开启...
- try {
- AOP实现...
- 被拦截函数...
- } catch {
- }
- 事务提交或者回滚...
2. 如果事务拦截的排序号高。
- AOP实现...
- try {
- 事务开启...
- 被拦截的函数...
- 事务提交...
- } catch {
- 事务回滚...
- }