Friday, October 12, 2012

Demystifying AOP, Getting started with LTW (load time weaving)

Often, using aspectj AOP, especially with LTW (load time weaving) is shrouded in mystery.
Thought I would write up a little note about getting started with Aspectj AOP LTW.

here goes...all you would need is a simple eclipse java project looking like below.

We would need 
  1. an aspect source file -
  2. a sample service which will get AOP-ed -
  3. a test class with main method -
  4. an Aspectj, LTW related config file - META-INF\aop.xml
  5. aspectjrt-1.7.0.jar and aspectjweaver-1.7.0.jar in your project classpath is the logging aspect. For further details about writing aspectj aspects please refer Listing of the simple aspect in java is below.

package com.ghag.rnd.aspects.ltw;

import org.aspectj.lang.ProceedingJoinPoint;

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

public class MySimpleLoggerAspect {
@Pointcut("execution(* *(..))")
public void myTraceCall() {
public Object myTrace(ProceedingJoinPoint joinPoint) throws Throwable
System.out.println("myTrace:before call "
Object retVal = null;
retVal = joinPoint.proceed();
System.out.println("myTrace:after call "+
+"."+joinPoint.getSignature().getName() + " retval=" +retVal);
return retVal;

} is as easy as given below:
package com.ghag.rnd.aspects.sample;

public class SampleService {
public String doService(String in){
System.out.println("inside doService");
return in;
} listing is a few more lines of code:
package com.ghag.test;

import com.ghag.rnd.aspects.sample.SampleService;

public class Tester {
public static void main(String[] args) {
new SampleService().doService("Ganesh Ghag");

And finally the META-INF\aop.xml listing is simple a self explanatory, especially the package names ;-)
<aspect name="com.ghag.rnd.aspects.ltw.MySimpleLoggerAspect" />
<!--  <weaver options="-verbose -debug -showWeaveInfo"> -->
<include within="com.ghag.rnd.aspects.sample.*" />
<include within="com.ghag.rnd.aspects.ltw.*" />

Now when you run, just ensure you have the following paramater supplied as JVM argument:
-javaagent:/your dev env local /path/to/aspectj\aspectjweaver-1.7.0.jar

Thats it folks, when you run,, SampleService call will get AOP-ed and give following output:
myTrace:before call com.ghag.rnd.aspects.sample.SampleService.doService
inside doService
myTrace:after call com.ghag.rnd.aspects.sample.SampleService.doService retval=Ganesh Ghag

Getting started with AspectJ AOP with LTW is that easy, folks!

No comments: