Search code examples
javaaopaspectjspring-aop

Converting Code based style to Annotation Based style AOP using Spring or AspectJ


I have the following code based style aspect which looks for a field level annotation in the code and calls a method with that field as argument. This is how it looks..

public aspect EncryptFieldAspect
{
    pointcut encryptStringMethod(Object o, String inString):
        call(@Encrypt * *(String))
        && target(o)
        && args(inString)
        && !within(EncryptFieldAspect);

    void around(Object o, String inString) : encryptStringMethod(o, inString) {
        proceed(o, FakeEncrypt.Encrypt(inString));
        return;
    }
}

The above method works fine, but I would like to convert it to Annotation based in Spring or AspectJ, something similar to this. Found AspectJ docs a bit confusing any hint would be helpful..

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

@Aspect
public class MyAspect {

    @Around("execution(public * *(..))")
    public Object allMethods(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
        System.out.println("Before...");
        try{
            return thisJoinPoint.proceed();
        }finally{
            System.out.println("After...");
        }
    }
}

Solution

  • Not sure which docs you were reading - the pages at https://eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html show you how to translate from code to annotation style. I will admit they aren't as comprehensive as they might be.

    Basically:

    • switch from aspect keyword to @Aspect
    • move your pointcut into a string @Pointcut annotation specified on a method
    • translate your advice from an unnamed block into a method. (This can get tricky for around advice because of the arguments to proceed)

    Your original becoming something like:

    @Aspect
    public class EncryptFieldAspect
    {
        @Pointcut("call(@need.to.fully.qualify.Encrypt * *(java.lang.String)) && target(o) && args(inString) && !within(need.to.fully.qualify.EncryptFieldAspect)");
        void encryptStringMethod(Object o, String inString) {}
    
        @Around("encryptStringMethod(o,inString)")
        void myAdvice(Object o, String inString, ProceedingJoinPoint thisJoinPoint) {
            thisJoinPoint.proceed(new Object[]{o, FakeEncrypt.Encrypt(inString)});
        }
    }