【问题标题】:How to define point cuts for a sequence of method(s)?如何为一系列方法定义切点?
【发布时间】:2014-12-09 18:41:08
【问题描述】:

例如,如果我有 3 个班级,

class A {
    public void doA() {
        /* do something */
    }
}

class B {
    public void doB() {
        A a = new A();
        a.doA();
    }
}

class MyClass {
    public static void main(String args[]) {
        B b = new B();
        b.doB();
    }
}

现在我想为流doB() -> doA()定义一个切入点,就像doB()调用doA()从A类和B类中获取参数并在方面方法中做一些事情。谁能帮帮我。

【问题讨论】:

    标签: aop aspectj spring-aop


    【解决方案1】:

    让我稍微扩展一下您的示例代码,以便让您了解我的解决方案能做什么和不能做什么:

    class A {
        public void doA() {}
    }
    
    class B {
        public void doB() {
            new A().doA();
            new C().doC();
        }
    }
    
    class C {
        public void doC() {
            new A().doA();
        }
    }
    
    class MyClass {
        public static void main(String args[]) {
            new A().doA();      // should not be captured
            new B().doB();      // should be captured
        }
    }
    

    如您所见,现在有一个新类C,我们现在有三个控制流:

    • MyClass.main -> A.doA
    • MyClass.main -> B.doB -> A.doA
    • MyClass.main -> B.doB -> C.doC -> A.doA

    您想排除#1 并捕获#2,但是#3 呢?在这种情况下,a.doA 从B.doB 通过C.doC 调用间接。我的解决方案也捕捉到了这种间接情况。如果这对您来说很好,或者在您的代码库中没有发生,您可以使用我的解决方案。否则事情会变得有点复杂,你需要检查调用堆栈。如果您需要排除 #2,请告诉我,我会扩展我的答案,但我可以保证,解决方案看起来不像这个那么简单。

    现在是方面:

    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class ControlFlowInterceptor {
        @Before("execution(void A.doA()) && target(a) && cflow(execution(void B.doB()) && target(b))")
        public void advice(JoinPoint thisJoinPoint, A a, B b) {
            System.out.println(thisJoinPoint);
            System.out.println("  " + a);
            System.out.println("  " + b);
        }
    }
    

    控制台输出如下所示:

    execution(void A.doA())
      A@7b19f779
      B@65c66812
    execution(void A.doA())
      A@4df2868
      B@65c66812
    

    请注意,我们在两个输出中都有相同的 B 对象 ID,但是因为 C.doC 创建了一个新的 A 对象,所以我们有两个不同的 A 对象 ID。

    【讨论】:

    • 谢谢@kriegaex,这就是我一直在寻找的:-)
    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多