0

我有两种交易方法,一种是另一种。当围绕方面没有设置方法时,事务注释工作得很好。调用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 -->
    }
}

方法A是这样的:

@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 --<
}
4

1 回答 1

3

你的方面如果有缺陷

  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;
        }   
    }
}
于 2014-05-20T09:36:33.090 回答