【问题标题】:how to associate one aspect method with multiple methods in aspectj?如何将一个方面方法与方面j中的多个方法相关联?
【发布时间】:2013-10-17 09:34:21
【问题描述】:

我有一堂课A:

@Service
public class A {
    public void goX()    {
        System.out.println("goX");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void goY()    {
        System.out.println("goY");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

还有一个 AOP 类 AOP:

@Aspect
@Service
class AOP        {
    @Around("execution(* com.test.A.goX(..))")
    public void calExecTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable        {
        long t1 = System.currentTimeMillis();
        proceedingJoinPoint.proceed();
        long t2 = System.currentTimeMillis();
        System.out.println(t2-t1);
    }
}

然后我可以通过方法AOP.calExecTime()来计算A.goX()执行的时间。

我想要的是用同样的方法AOP.calExecTime() 计算A.goX() 和A.goY() 的时间,我不知道如何在@Around 注释中写东西。谁能帮帮我?非常感谢。

【问题讨论】:

    标签: java annotations aspectj


    【解决方案1】:

    这会有所帮助。

    @Aspect
    @Service
    class AOP        {
    @Around("within(* com.test.*)")
    public void calExecTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long t1 = System.currentTimeMillis();
        proceedingJoinPoint.proceed();
        long t2 = System.currentTimeMillis();
        System.out.println("Method "+ proceedingJoinPoint.getSignature().getName() + " time : "+  t2-t1);
    
        }
    
       }
    

    【讨论】:

    • 感谢您的回复!如果goX 和goY 在不同的班级怎么办?如果有什么方法可以在@Around中写AND?
    • 是的,您可以使用 inside(you package.*) 而不是执行。无论你在这个包中有多少类,你的方法 calExecTime 都会为所有类调用。但是请确保这不会造成任何内存问题。我在答案中更新了相同的内容。也请在这里了解更多关于 AOP 的信息。 docs.spring.io/spring/docs/2.5.x/reference/aop.html
    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多