allows you to reuse certain advice across multiple AOP implementations that support the AOP Alliance
interfaces.
"Hello World!" in AOP
Before we dive into discussing the Spring AOP implementation in detail, we want to present a simple
example to provide some context for these discussions. In this example, we take a simple class that
outputs the message "World," and then using AOP, we transform an instance of this class at runtime to
output "Hello World!" instead. Listing 6-1 shows the basic MessageWriter class.
Listing 6-1. The MessageWriter Class
package com.apress.prospring3.ch6;
public class MessageWriter {
public void writeMessage() {
System.out.print("World");
}
}
The MessageWriter class is nothing special; it has just one method that writes the message "World"
to console output. We want to advise--that is, add some advice to--this class so that the writeMessage()
method actually writes "Hello World!" instead.
To do this, we need to execute some code before the method body executes to write "Hello," and we
need to execute some code after the method body executes to write "!" to this. In AOP terms, what we
need is an around advice--that is, advice that executes around a joinpoint. In this case, the joinpoint is
the invocation of the writeMessage() method. Listing 6-2 shows the implementation of the around
advice, the MessageDecorator class.
Listing 6-2. Implementing Around Advice
package com.apress.prospring3.ch6;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MessageDecorator implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.print("Hello ");
Object retVal = invocation.proceed();
System.out.println("!");
return retVal;
}
}
The MethodInterceptor interface is the AOP Alliance standard interface for implementing around
advice for Method Invocation joinpoints. The MethodInvocation object represents the Method
Invocation that is being advised, and using this object, we control when the Method Invocation is
actually allowed to proceed. Because this is around advice, we are essentially capable of performing
some actions before the method is invoked and some actions after it is invoked but before it returns. In
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home