【问题标题】:can we have mutiple pointcuts mapped to a single advice我们可以将多个切入点映射到单个建议吗
【发布时间】:2015-01-08 10:55:15
【问题描述】:

在 aspectj 中,我们可以将多个切入点映射到单个通知吗?

例如下面是两个独立的切入点

@Pointcut("execution(* xyz.get(..))")
    void pointcut1() {
    }

@Pointcut("execution(* abc.put(..))")
    void pointcut2() {
    }

那么任何人都可以给出如何在一个建议上配置这两个切入点的想法吗?

因为对于像下面这样的单个切入点到单个建议,我们有

@Before("pointcut1()")
    public void beforeLogging() {
        System.out.println("Before Methods");
    }

如何为多个切入点配置相同的建议?

【问题讨论】:

  • 因为有人刚刚对我的回答投了赞成票,所以我注意到这个老问题仍然被列为未决问题,尽管有两个有用的答案。请选择一个接受并投票以结束问题。谢谢。

标签: spring aop aspectj spring-aop pointcut


【解决方案1】:

是的,您可以将切入点与逻辑 AND (&&) 以及逻辑 OR(||) 运算符结合起来,或者通过逻辑 NOT (!) 将它们取反。

你可能想要的是这个:

@Before("pointcut1() || pointcut2()")

这里的 OR 是有意义的,因为在您的示例中,逻辑 AND 总是会导致一个空集:一个方法不能同时在两个包中,而是在其中一个包中。

【讨论】:

    【解决方案2】:

    您可以使用 ||操作员。 来自文档http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html(9.2.2 声明一个方面):

    @Pointcut("execution(public * (..))")
    private void anyPublicOperation() {}
    
    @Pointcut("within(com.xyz.someapp.trading..)")
    private void inTrading() {}
    
    @Pointcut("anyPublicOperation() || inTrading()")
    private void tradingOperation() {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多