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

匆匆过客 提交于 2019-12-12 04:05:17

问题


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...");
        }
    }
}

回答1:


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)});
    }
}


来源:https://stackoverflow.com/questions/36974974/converting-code-based-style-to-annotation-based-style-aop-using-spring-or-aspect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!