更新:
好的,我可以在此页面上找到最佳参考:注释,切入点和建议。
您可以匹配方法,但是将无法捕获参数(仅方法和注释)。因此,您将要做的是切入点匹配和反射的结合。像这样:
@Pointcut( "execution(@com.xxx.xxx.annotation.MyAnnotationForMethod * *(.., @com.xxx.xxx.annotation.MyAnnotationForParam (*), ..))")public void annotatedMethod(){}@Before("annotatedMethod()")public void doStuffonParam(final JoinPoint jp){ final Signature signature = jp.getSignature(); if(signature instanceof MethodSignature){ final MethodSignature ms = (MethodSignature) signature; final Method method = ms.getMethod(); final String[] parameterNames = ms.getParameterNames(); final Class<?>[] parameterTypes = ms.getParameterTypes(); final Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for(int i = 0; i < parameterAnnotations.length; i++){ final Annotation[] annotations = parameterAnnotations[i]; final MyAnnotationForParam paramAnnotation = getAnnotationByType(annotations, MyAnnotationForParam.class); if(paramAnnotation != null){ this.processParameter(ms.toShortString(), parameterNames[i], parameterTypes[i], paramAnnotation); } } }}@SuppressWarnings("unchecked")private static <T extends Annotation> T getAnnotationByType(final Annotation[] annotations, final Class<T> clazz){ T result = null; for(final Annotation annotation : annotations){ if(clazz.isAssignableFrom(annotation.getClass())){ result = (T) annotation; break; } } return result;}private void processParameter(final String signature, final String paramName, final Class<?> paramType, final MyAnnotationForParam paramAnnotation){ System.out.println(MessageFormat.format( "Found parameter ''{0}'' n of type ''{1}'' n with annotation ''{2}'' n in method ''{3}''", paramName, paramType, paramAnnotation, signature));}这是我针对上述方面的测试课程:
public class TestClass{ @MyAnnotationForMethod public void simpleTestMethod(@MyAnnotationForParam final String param1){ System.out.println("Method body (simple)"); }; @MyAnnotationForMethod public void complexTestMethod(final String param1, @MyAnnotationForParam final Float param2, @MyAnnotationForParam final Boolean param3){ System.out.println("Method body (complex)"); }; public static void main(final String[] args){ System.out.println("Starting up"); final TestClass testObject = new TestClass(); testObject.simpleTestMethod("Hey"); testObject.complexTestMethod("Hey", 123.4f, false); System.out.println("Finished"); }}这是输出:
Starting upFound parameter 'param1' of type 'class java.lang.String' with annotation '@com.xxx.xxx.annotation.MyAnnotationForParam()' in method 'TestClass.simpleTestMethod(..)'Method body (simple)Found parameter 'param2' of type 'class java.lang.Float' with annotation '@com.xxx.xxx.annotation.MyAnnotationForParam()' in method 'TestClass.complexTestMethod(..)'Found parameter 'param3' of type 'class java.lang.Boolean' with annotation '@com.xxx.xxx.annotation.MyAnnotationForParam()' in method 'TestClass.complexTestMethod(..)'Method body (complex)Finished
暗示
您可能会想缓存很多,而无需在每次执行中解析每个批注的每个参数。保留哪个方法的哪个参数带有注释的映射,并仅处理那些参数。



