Conditional Pointcut in AspectJ
Well, I came to a situation in which i wanted my advice for the pointcut to be executed on some conditions.
You may be thinking, why not just put a condition inside the advice itself. Yeah, that's kind of workaround.
AspectJ has given way to use condition in pointcut itself to filter your execution, similar to java.
Let us understand this with an example.
1. Consider I have an Advice for a pointcut, on execution ,in getting the price of car, to do some logging.
pointcut getPriceOnCall() : execution(Double com.test.java.Vehicle.getPrice());
Double around(): getPriceOnCall(){
System.out.println("this: " + thisJoinPoint.getThis());
System.out.println("this: " + thisJoinPointStaticPart.toLongString());
LOGGER.log(Level.INFO, "just after call and before starting execution");
Double price= proceed();
LOGGER.log(Level.INFO, "preceed called");
return price;
}
2. I want to have a logging only when car's minimum price is greater than some value.
Then, here we can use if(true) or if(false) pointcut.
pointcut getPriceOnCall() : execution(Double com.test.java.Vehicle.getPrice()) && if(((Vehicle)thisJoinPoint.getThis()).getMinPrice()>30000);
Double around(): getPriceOnCall(){
System.out.println("this: " + thisJoinPoint.getThis());
System.out.println("this: " + thisJoinPointStaticPart.toLongString());
LOGGER.log(Level.INFO, "just after call and before starting execution");
Double price= proceed();
LOGGER.log(Level.INFO, "preceed called");
return price;
}
Here You can see that I have put a condition with if(...) pointcut. So only when this condition is true then only this advice is going to be executed.
When using the annotation style, it is not possible to write a full Java expression within the annotation value so the syntax differs slightly, whilst providing the very same semantics and runtime behaviour. An if() pointcut expression can be declared in an @Pointcut , but must have either an empty body (if(), or be one of the expression forms if(true) or if(false) . The annotated method must be public, static, and return a boolean. The body of the method contains the condition to be evaluated. For example:
@Pointcut("call(* *.*(int)) && args(i) && if()") public static boolean someCallWithIfTest(int i) { return i > 0; }
-----------------------------------------------------------------------------------------------------------
Cheers!!!