can we have mutiple pointcuts mapped to a single advice

1.1k views Asked by At

In aspectj , can we have multiple pointcuts mapped to the single advice ?

for example below are two separate pointcuts

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

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

so can anyone give idea how to configure these two pointcuts on a single advice ?

because for single pointcut to single advice like below we have

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

how to configure the same advice for multiple pointcuts ?

2

There are 2 answers

0
Evgeni Dimitrov On

You can use the || operator. From the docs http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html (9.2.2 Declaring an aspect):

@Pointcut("execution(public * (..))")
private void anyPublicOperation() {}

@Pointcut("within(com.xyz.someapp.trading..)")
private void inTrading() {}

@Pointcut("anyPublicOperation() || inTrading()")
private void tradingOperation() {}
0
kriegaex On

Yes, you can combine pointcuts with logical AND (&&) as well as logical OR(||) operators or negate them by logical NOT (!).

What you probably want here is this:

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

The OR makes sense here because in your example a logical AND would always lead to an empty set: a method cannot be in two packages at the same time, but in one of them alternatively.