Java Reference
In-Depth Information
Figure 7.4. Spring AOP in action.
ChangeLogger
is a Java aspect that logs a message before each set method.
UpdateReporter
does the same in Groovy but reports on existing values. The
GroovyAspect
is an inline
scripted bean defined inside the configuration file.
The following listing shows an example of an aspect, using Spring annotations, written in
Java. This aspect is applied whenever a
set
method is about to be called, and it logs which
method is being invoked and what the new value will be.
Listing 7.14. A Java aspect that logs changes to properties
package
mjg.aspects;
import
java.util.logging.Logger;
import
org.aspectj.lang.JoinPoint;
import
org.aspectj.lang.annotation.Aspect;
import
org.aspectj.lang.annotation.Before;
@Aspect
public class
ChangeLogger {
private
Logger log = Logger.
getLogger
(
ChangeLogger.
class
.getName());
@Before("execution(void set*(*))")
public void
trackChange(JoinPoint jp) {
String method = jp.getSignature().getName();
Object newValue = jp.getArgs()[0];
log.info(method + " about to change to " +
newValue + " on " + jp.getTarget());
}
}