【问题标题】:Spring @Transactional wont rollback after putting aspect around methodSpring @Transactional 在将方面放在方法之后不会回滚
【发布时间】:2014-05-20 08:46:57
【问题描述】:

我有两种交易方法,一种是另一种。当围绕方面没有设置方法时,事务注释工作得很好。调用methodA之后我们调用methodB,methodB在DB中写入一些东西,然后我们在methodA中返回,抛出异常,然后methodB回滚。 但是当我把我的方面放在方法A上时,方法B不会回滚。我无法弄清楚那里发生了什么。我尝试了许多传播属性的组合,但似乎都没有。 提前致谢。 我使用 Spring 2.5.4

我在 applicationContext.xml 中有这个配置:

<!-- Aspect -->
<bean id="logAspect" class="LoggingAspect" />
<aop:config>
    <aop:aspect id="aspectLoggging" ref="logAspect" >
        <aop:pointcut id="testAround" expression="execution(* methodA(..))" />
        <!-- @Around -->
        <aop:around method="logProcess" pointcut-ref="testAround" />
    </aop:aspect>
</aop:config>

我的 LoggingAspect 类是这样的:

@Aspect
public class LoggingAspect {
    public void logProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        <!-- some code before -->
        try {
            Object result = joinPoint.proceed();
        } catch (Exception e) {
            log.info(e.getMessage());
            <!-- some code here -->     
        }   

        <!-- some code after -->
    }
}

MethodA 是这样的:

@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
public something methodA() throws Exception {
    methodB();
    ...
    throw new Exception("message ...");
    ...
}

方法B是这样的:

@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
public void methodB() throws Exception {
    <!-- insert something in db --<
}

【问题讨论】:

标签: spring transactions rollback transactional aspect


【解决方案1】:

如果有缺陷,你的方面

  1. 您必须始终从周围方面返回 Object
  2. 永远不要捕获并吞下异常
public void logProcess(ProceedingJoinPoint joinPoint) throws Throwable { ... }

您的切面有一个void 方法,它应该是Object,并且您应该始终将调用结果返回给proceed()

接下来,您将捕获并吞下异常(如果可能发生),如果您不这样做,则应始终重新抛出异常,这会破坏正确的 tx,管理。

你的方面应该看起来更像这个。

@Aspect
public class LoggingAspect {
    public Object logProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        <!-- some code before -->
        try {
            Object result = joinPoint.proceed();
            <!-- some code after -->
            return result;
        } catch (Exception e) {
            log.info(e.getMessage());
            <!-- some code here -->     
            throw e;
        }   
    }
}

【讨论】:

  • 现在它完全按照我的意愿工作了。感谢您及时详细的回复。
猜你喜欢
  • 1970-01-01
  • 2016-05-03
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2013-06-17
  • 1970-01-01
  • 2018-01-12
相关资源
最近更新 更多