【问题标题】:Intercept a method only if that method is called from a certain class?仅当从某个类调用该方法时才拦截该方法?
【发布时间】:2021-06-08 21:23:42
【问题描述】:

使用 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();

}

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

【问题讨论】:

    标签: java spring aop interceptor


    【解决方案1】:

    使用 AspectJ 或 Spring Aop(没关系),是否只有在某个类中调用该方法时才能拦截该方法?

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

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

    上述所有仅在 AspectJ 中有效的原因是 Spring AOP 既不支持 call() 也不支持 cflow(),如文档中的 here 所述。

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

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


    更新:此处引用了我的其他答案:


    更新 2: 更未知的角落或 Spring AOP 之一是 ControlFlowPointcut 类。 Spring手册mentions it briefly without example,但是有一个test in the Spring source code,我找到了一个example on a 3rd-party website。它不能帮助您直接解决问题,但我可以想到一种解决方案,您可以在其中为每个允许的源类创建一个这样的切入点,并将每个切入点链接到实现您想要的方面行为的同一个顾问。这会很慢,因为 Spring 使用反射和调用堆栈,需要一些样板代码来手动连接所有内容,但它会起作用。

    【讨论】:

    • 这个答案比副本中提供的要完整得多
    • @dreamcrash 那么也许这个问题应该作为这个问题的欺骗而被关闭。毕竟,重复的链接应该会导致最佳答案。
    • @Gimby 我其实也是这么想的,我不确定是否真的有重复,接缝会略有不同,不幸的是,目前我没有时间去仔细考虑他们
    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多