Tuesday, May 25, 2010

AspectJ Load-Time Weaving

AspectJ has two weaving models, build-time and load-time. Here I'm gonna talk about binary load-time weaving. The good thing about it is that we can create a separate Java project and AspectJ project and weave them at runtime. This can be achieved thanks to JVMTI. Hence, it requires Java 5 and above.

Let's say we have a Java project called my-java-project.

package myproject;

public class HelloWorld {
    public void sayHello(String message) {

package myproject;

public class Main {

    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.sayHello("Hello World");

And an AspectJ project called my-aspectj-project.

package myproject;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

public class HelloWorldAspect {

    @Around("execution(* myproject.HelloWorld.sayHello(..))")
    public Object aroundAspect(ProceedingJoinPoint joinPoint) {
        System.out.println("Before sayHello()");
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
        System.out.println("After sayHello()");
        return obj;

Here we also need to add META-INF/aop.xml inside this AspectJ jar.

<?xml version="1.0" encoding="UTF-8"?>
        <aspect name="myproject.HelloWorldAspect" />

To run, execute this from the commaand line.
java -javaagent:aspectjweaver-1.5.4.jar -cp my-aspectj-project-0.0.1-SNAPSHOT.jar:my-java-project-0.0.1-SNAPSHOT.jar:aspectjrt-1.6.7.jar myproject.Main

No comments:

Post a Comment