javaspring-bootjava-annotationsspring-aspects

Is there anyway to create a Spring Aspect advice that triggers on any method that is NOT annotated by certain annotation?


Basically I am trying to create a log system that will log most of the controller methods (their parameters, bodies, status codes and so on), however, there are few controller methods I do not want to log for some specific reasons. I do not want to create an annotation that indicates this method will be logged (because there are gonna be plenty), instead, I want to create an annotation that indicates this method should NOT be logged. Obviously, I cannot negate an annotation in a Spring Aspect advice, so is there any workaround for it? (such as getting a method's all annotations from ProceedingJoinPoint, then check if they contain that NoLog annotation)


Solution

  • MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = joinPoint.getTarget().getClass()
          .getMethod(methodSignature.getMethod().getName(),
                     methodSignature.getMethod().getParameterTypes());
    CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
    

    Well, looks like you can use the above codes to attempt to get the CustomAnnotation on your methods, if your methods are NOT annotated by this CustomAnnotation, a null will be returned, otherwise a Proxy object will be returned