使用 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...");
}
}
}
推荐答案
不确定您正在阅读哪些文档 - https://eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html 向您展示如何从代码转换为注释样式.我承认它们并不像它们想象的那么全面.
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 注释中
- 将您的建议从未命名的块转换为方法.(由于要继续进行的争论,这对于周围的建议来说可能会变得棘手)
你原来的样子:
@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屋!