Thursday, July 14, 2011

AOP - Notes on Advice

An advice has the following syntax:
advice_type([arg]) : pointcut_name { advice_body }

There are three types of Advice
1. Before, the advice is executed right before the join point code is executed.

Example of a before advice:

/** pointcut */
private pointcut getNameField() : get(private String edu.mat.hello.MessageCommunicator.name);

/** advice */
before() : getNameField() {
System.out.println("Getter method is about to call.");
}

2. After, the advice is executed right after the join point code is executed.

/** pointcut */
private pointcut setNameField() : set(private String edu.mat.hello.MessageCommunicator.name);

/** advice: this advise is executed whether setNameField() returns normally or throwing exception */
after() : setNameField() {
System.out.println("Name has been set.");
}

/** advice: this advise is executed only when setNameField() returns successfully */
after() returning : setNameField() {
System.out.println("Name has been set.");
}

To get the returned object, we can use after() returning(Integer count) : calculateRevenue() {...}

/** advice: this advise is executed only when setNameField() throws exception */
after() throwing : setNameField() {
System.out.println("Name has not been set.");
}

To get the thrown exception, we can use after() throwing (Exception e) : calculateRevenue() {...}

3. Around, this advice is useful to intercept an execution of a join point.

Suppose we have the following pointcut:

private pointcut sayHello(edu.mat.hello.MessageCommunicator caller, String person) : call(* edu.mat.hello.MessageCommunicator.sayHello(String, String)) && args(person, String) && target(caller);

The above pointcut says that we will capture all join points in sayHello(String, String) method of class MessageCommunicator, capture the method caller (target object as shown in target(caller)) and first parameter of the method (as shown in args(person, String)) as stated in pointcut's arguments.

Then we have an advice as in:

void around(edu.mat.hello.MessageCommunicator caller, String person) : sayHello(caller, person) {
try {
proceed(caller, "Pak " + person);
} catch (Exception e) {

} finally {
System.out.println("Say hello finally finished.");
}
}

there, we execute the real join point code in proceed(caller, "Pak " + person); and surround it with try-catch block. The arguments in proceed must match arguments in around().

0 comments:

 

©2009 Stay the Same | by TNB