【问题标题】:Spring aop not triggered on one method but triggered on the other method [duplicate]Spring aop未在一种方法上触发,但在另一种方法上触发[重复]
【发布时间】:2016-11-09 04:08:18
【问题描述】:

我使用 AOP 将监视器与业务逻辑分开。但是当我使用junit测试我的aop代码时,我发现执行方法B时不会触发AOP,而是执行方法A时会触发AOP。方法 B 调用方法 A。

我的伪代码如下:

@Aspect
public class TimeMonitor {
    @Pointcut("execution( * MainClass.A(..))")
    public void pointA();
    @Around("pointA()")
    Object monitorA(ProceedingJoinPoint jp ){
        try{
            jp.proceed();
        }catch(Exception e){
            logger.error("failed to execute A in TimeMonitor");
        }
    }

我的主要逻辑如下:

public class MainClass{
    public String A(){
    }
    public String B(){
        try{
            A();//call method A
        }catch(Exception e ){
            logger.error("failed to execute A in Main class");
        }
    }
}

然后当我用 Junit 进行单元测试时:

public TimeMonitorTest{
    @Test
    public void TestA(){
        //test code here
        A();
        //AOP method monitorA will be triggered;
    }
    @Test
    public void TestB(){
        B();
        //AOP method monitorA will not be triggered;
    }
}

那为什么我在MainClass中测试方法B时monitorA()没有被触发?

谁能帮帮我?

谢谢!!

【问题讨论】:

  • 你到底是怎么调用 A();在TestA中
  • 您可以重新格式化您的代码并为您的方法使用小写字母开头吗? A() 在 java 中看起来像构造函数而不是方法。还有你如何在你的测试课上打电话A()?你不应该先实例化MainClass,然后从中调用A()吗?我怀疑你的TimeMonitorTest 是否可以编译。

标签: spring aop spring-aop


【解决方案1】:

这是一个经典的 Spring AOP 问题,在这里被问过很多次。您使用 Spring AOP,一种基于代理的“AOP lite”方法。因此,只有在真正从类外部调用公共的、非静态的代理方法时,才会触发处理 AOP 的动态代理子类。内部方法调用不使用代理,而是直接转到原始对象的目标方法。您在测试中看到的行为是意料之中的。

Spring AOP manual, chapter "Understanding AOP proxies" 中也解释了这一事实(在此处查找术语“自我调用”)。它还描述了 AspectJ 不存在这种自调用问题,因为 AspectJ 不是基于代理的,而是一个成熟的 AOP 框架。

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多