使用Spring或AspectJ将基于代码的样式转换为基于注释的样式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;
}
}
上述方法可以正常工作,但是我想将其转换为基于Spring或AspectJ的Annotation,与此类似.找到AspectJ文档有点混乱的任何提示都会有所帮助.
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...");
}
}
}
推荐答案
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.
基本上:
- 从Aspect关键字切换为@Aspect
- 将切入点移动到方法中指定的字符串@Pointcut批注中
- 将您的建议从一个未命名的块转换为一个方法. (由于要进行的论点,对于周围的建议这可能会比较棘手)
您的原始照片变成了类似的东西
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)});
}
}
这篇关于使用Spring或AspectJ将基于代码的样式转换为基于注释的样式AOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!