仅当从某个类调用该方法时才拦截该方法?

Pre*_*sto 2 java aop spring interceptor

使用 AspectJ 或 Spring Aop(无关紧要),是否可以仅在从某个类中调用该方法时才拦截该方法?

例子:

public class House() {

    String address;

    public House(String address) {
       this.address = address;
    }   
   
    public String getAddress() {
      return this.address();
   }
}


public class BadHouse() {

    public void doNotIntercept() {
      House h = new House("1234");
      h.getAddress();
   }
}

public class GoodHouse() {
     
     public void intercept() {
     House h = new House("4567");
     h.getAddress();
    }

}

public class houseInterceptor() {

     @Before("execution(com.example.House.getAddress(..))")
     // only intercept on GoodHouse.class??? 
     public void beforeGetAddress();

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下可以使用“within”吗?谢谢

kri*_*aex 5

使用 AspectJ 或 Spring Aop(无关紧要),是否可以仅在从某个类中调用该方法时才拦截该方法?

使用 AspectJ 是可能的(在 Spring 中使用与否,没关系),但不适用于 Spring AOP,因为您需要

  • 使用call()切入点和JoinPoint.EnclosingStaticPart(注释样式)或thisEnclosingJoinPointStaticPart(本机语法)的组合,当且仅当您要检查直接调用者时,
  • 或者使用call()切入点和的组合this(),再次当且仅当您要检查直接调用者时,
  • 如果您想检查可能的间接调用者(例如? ? ),或者使用call()orexecution()cflow()orcflowbelow()切入点的组合。GoodHouseFooHouse

以上所有内容仅在 AspectJ 中有效的原因是 Spring AOP 既不支持call()也不支持cflow(),如此处所述

在这种情况下可以使用“within”吗?

不,within()在这种情况下对您没有帮助。


更新:这里引用了我的其他答案:


更新 2:更不为人知的角落或 Spring AOP 之一是ControlFlowPointcut类。Spring手册中简单的提到了它,没有举例,但是在Spring源代码中有一个测试,我在一个3rd方网站上找到了一个例子。它不能帮助您直接解决您的问题,但我可以想到一种解决方案,您可以在其中为每个允许的源类创建一个这样的切入点,并将每个切入点链接到实现您想要的方面行为的同一个顾问程序。这会很慢,因为 Spring 使用反射和调用堆栈,需要一些样板代码来手动连接所有东西,但它可以工作。