在我的应用程序中,我有一些方法的参数带有一些注释.现在,我想编写Aspect,使用来自注释属性的信息对带注释的参数进行一些预处理.例如,方法:
public void doStuff(Object arg1, @SomeAnnotation CustomObject arg1, Object arg2){...}
方面:
@Before(...)
public void doPreprocessing(SomeAnnotation annotation, CustomObject customObject){...}
@Before应该写什么?
编辑:
谢谢大家.我有解决办法:
@Before("execution(public * *(.., @SomeAnnotation (*), ..))")
public void checkRequiredRequestBody(JoinPoint joinPoint) {
MethodSignature methodSig = (MethodSignature) joinPoint.getSignature();
Annotation[][] annotations = methodSig.getMethod().getParameterAnnotations();
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
for (Annotation annotation : annotations[i]) {
if (SomeAnnotation.class.isInstance(annotation)) {
//... preprocessing
}
}
}
}
解决方法:
您可以这样做:
@Before("execution(* com.foo.bar.*.doStuff(..)) && args(arg1, arg2)")
public void logSomething(JoinPoint jp, CustomObject arg1, Object arg2) throws Throwable {
MethodSignature methodSignature = (MethodSignature) jp.getSignature();
Class<?> clazz = methodSignature.getDeclaringType();
Method method = clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
SomeAnnotation argumentAnnotation;
for (Annotation ann : method.getParameterAnnotations()[0]) {
if(SomeAnnotation.class.isInstance(ann)) {
argumentAnnotation = (SomeAnnotation) ann;
System.out.println(argumentAnnotation.value());
}
}
}
这是参数类型的自定义注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SomeAnnotation {
String value();
}
以及要拦截的方法:
public void doStuff(@SomeAnnotation("xyz") CustomObject arg1, Object arg2) {
System.out.println("do Stuff!");
}
你不能那样做
@Before(...)
public void doPreprocessing(SomeAnnotation annotation, CustomObject customObject){...}
因为注释不是参数,所以只能在其中引用参数.
您可以使用@args(annot)来完成操作,但这仅与放在参数类型本身上的注释匹配,而不与实际参数前面的注释匹配. @args(annot)适用于以下情况:
@SomeAnnotation
public class CustomObject {
}