Spring aop 不是在一种方法上触发而是在另一种方法上触发 [英] Spring aop not triggered on one method but triggered on the other method

查看:31
本文介绍了Spring aop 不是在一种方法上触发而是在另一种方法上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use AOP to separate monitor from the bussiness logic. But when I use junit to test my aop code I found that AOP are not triggered when method B is executed but are triggered when method A is executed. And method B calls method 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 进行单元测试时:

Then when I do unit test with 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()?

So why monitorA() not be triggered when I test method B in MainClass?

有人可以帮我吗?

谢谢!!

推荐答案

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

This is a classic Spring AOP question and has been asked many times here. You use Spring AOP, a proxy-based "AOP lite" approach. Thus, dynamic proxy subclasses taking care of AOP are only triggered if public, non-static proxy methods are really called from outside the class. Internal method calls do not use the proxy but go directly to the target method of the original object. The behaviour you see in your test is to be expected.

这一事实也在Spring AOP 手册,理解 AOP 代理"一章(在那里寻找术语自调用").它还描述了 AspectJ 没有这种自调用问题,因为 AspectJ 不是基于代理的,而是一个成熟的 AOP 框架.

This fact is also explained in the Spring AOP manual, chapter "Understanding AOP proxies" (look for the term "self-invocation" there). It also describes that AspectJ does not have this self-invocation issue because AspectJ is not proxy-based but a full-fledged AOP framework.

这篇关于Spring aop 不是在一种方法上触发而是在另一种方法上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆