joinpoint for example custom annotation advice java annotations aop aspectj

java - custom - spring aop for logging example



Obtener parĂ¡metros anotados dentro de un punto de corte (2)

Tengo dos anotaciones @LookAtThisMethod y @LookAtThisParameter , si tengo un punto de corte alrededor de los métodos con @LookAtThisMethod ¿cómo puedo extraer los parámetros de dicho método que están anotados con @LookAtThisParameter ?

Por ejemplo:

@Aspect public class LookAdvisor { @Pointcut("@annotation(lookAtThisMethod)") public void lookAtThisMethodPointcut(LookAtThisMethod lookAtThisMethod){} @Around("lookAtThisMethodPointcut(lookAtThisMethod)") public void lookAtThisMethod(ProceedingJoinPoint joinPoint, LookAtThisMethod lookAtThisMethod) throws Throwable { for(Object argument : joinPoint.getArgs()) { //I can get the parameter values here } //I can get the method signature with: joinPoint.getSignature.toString(); //How do I get which parameters are annotated with @LookAtThisParameter? } }


Modelé mi solución alrededor de esta otra respuesta a una pregunta diferente pero similar.

MethodSignature signature = (MethodSignature) joinPoint.getSignature(); String methodName = signature.getMethod().getName(); Class<?>[] parameterTypes = signature.getMethod().getParameterTypes(); Annotation[][] annotations = joinPoint.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations();

La razón por la que tuve que pasar por la clase de destino fue porque la clase anotada era una implementación de una interfaz y, por lo tanto, signature.getMethod().getParameterAnnotations() devolvió el valor nulo.


final String methodName = joinPoint.getSignature().getName(); final MethodSignature methodSignature = (MethodSignature) joinPoint .getSignature(); Method method = methodSignature.getMethod(); GuiAudit annotation = null; if (method.getDeclaringClass().isInterface()) { method = joinPoint.getTarget().getClass() .getDeclaredMethod(methodName, method.getParameterTypes()); annotation = method.getAnnotation(GuiAudit.class); }

Este código cubre el caso donde el Método pertenece a la interfaz.