As I already said, an advice is the code to be executed at a join point that has been selected by a pointcut. There exist three types of advices: the before, after and around advice. The before advice executes before the execution of a join point, the after advice after the execution of a join point and the around advice surrounds the join point’s execution. We will now look at each advice in turn.
Before advice:
- Structure:
before() : <Pointcut> {
…
} - Example:
before() : call(* MyClass.myMethod()) {
System.out.println(”about to execute MyClass.myMethod()”);
}
After advice:
- Structure:
after() : <Pointcut> {
…
}after() returning(<ReturnType returnObject>) : <Pointcut> {
…
}after() throwing(<ExceptionType exceptionObject>) : <Pointcut> {
…
} - Example:
after() : call(* MyClass.myMethod()) {
System.out.println(”executed MyClass.myMethod()”);
}after() returning(int result) : call(* int MyClass.myMethod()) {
System.out.println(”The method MyClass.myMethod() returned ” + result);
}after() throwing(Exception e) : call(* int MyClass.myMethod() throws Exception) {
System.out.println(”The method MyClass.myMethod() threw the exception ” + e);
} - Explanation:
As you can see is it also possible to capture the result of a method call or the exception the method threw. You can deal with these the same way you do with normal arguments/parameters.
Around advice:
- Explanation:
The before and after advice are quite simple. But the around advice will need a little more explanation.
If you do not explicitly call the method proceed() in the around advice the originally called method won’t be executed. The method will then just be bypassed. When calling proceed() you must pass the same number and types of arguments as collected by the advice. The proceed() method will also return the result of the method call.
Another thing you have to do is specifying the return type the adviced join point has. If you are not sure what the return type of the join point is because you capture multiple different join points independent of their return type use Object. AspectJ will then automatically adjust the type based on the return type of the particular join point. - Structure:
<returnType> around() : <Pointcut> {
…
} - Example:
int around() : call(* int MyClass.myMethod()) {
// doSomething
int result = proceed(); //
// doAnotherThing
return result;
}
