javaspringreflectionaop

AOP: Check if specific argument is annotated


Spring boot, AOP. I want to find out which argument is annotated with specific annotation. I have @Aspect:

@Component
@Aspect
@RequiredArgsConstructor
public class CheckMyAop {


    @Around("@annotation(com.x.service.annotations.MyAnnotation)")
    public Object myChecker(ProceedingJoinPoint joinPoint) throws Throwable {

The joinPoint.getArgs() doesn't allow to check if certain argument is annotated. So how to find it out? Using reflection go through all class methods find corresponding method (with matching name and matching all arguments) and then check if that argument is annotated? Something like this?

        Class c = ((MethodInvocationProceedingJoinPoint) joinPoint).getSignature().getDeclaringType();
        String aopTriggeredMethodName = ((MethodInvocationProceedingJoinPoint) joinPoint).getSignature().getName();
        for (Method m : c.getMethods()) {
           if (m.getName().equals(aopTriggeredMethodName)) {

Solution

  • You need to get the method and then the parameter annotations:

    MethodSignature methodSig = (MethodSignature) joinpoint.getSignature();
    Annotation[][] annotations = methodSig.getMethod().getParameterAnnotations();
    

    Then check if it has your annotation. You shouldn't do reflection on every call though since it is expensive. You should cache the knowledge.