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

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

问题描述

我使用AOP将监视器与业务逻辑分开.但是,当我使用junit测试我的aop代码时,我发现AOP在执行方法B时不会触发,而在执行方法A时会触发.然后方法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.

(在此查找自我调用"一词).它还描述了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天全站免登陆