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.

HelloWorld.java
package myproject;

public class HelloWorld {
    
    public void sayHello(String message) {
        System.out.println(message);
    }
}

Main.java
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.

HelloWorldAspect.java
package myproject;

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

@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) {
            e.printStackTrace();
        }
        System.out.println("After sayHello()");
        return obj;
    }
}

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

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

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