Spring AOP: Getting parameters of the pointcut annotation

前端 未结 2 2067
北海茫月
北海茫月 2020-12-14 02:43

Consider I have defined the following aspect:

@Aspect
public class SampleAspect {

    @Around(value=\"@annotation(sample.SampleAnnotation)\")
    public Obj         


        
相关标签:
2条回答
  • 2020-12-14 02:56

    Change the advice signature to

    @Around(value="@annotation(sampleAnnotation)")
    public Object display(ProceedingJoinPoint joinPoint, SampleAnnotation sampleAnnotation ) throws Throwable {
        // ...
    }
    

    and you will have access to the value in the annotation.

    See docs for more info.

    0 讨论(0)
  • 2020-12-14 02:59

    Bellow I'll add a complete example of AOP implementation where I'll getting parameter from my Custom pointCut annotation, where my advice aim to calculate the time execution of a function:

    1- Custom Annotation:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AnnotationLogExecutionTime {
    
        public boolean isActivate() default false;
    
    }
    

    2- Controller:

    @AnnotationLogExecutionTime(isActivate = true)
    @PostMapping("/connection")
    public HttpEntity<String> createAuthenticationToken(HttpServletRequest request,
                                                            @RequestBody AuthenticationRequest authenticationRequest) {...}
    

    3- Advice

    @Component
    @Aspect
    public class LoggingExecutionTimeAdvice {
    
        @Around("@annotation(annotationLogExecutionTime)")
        public Object logExecutionTime(ProceedingJoinPoint joinPoint, AnnotationLogExecutionTime annotationLogExecutionTime) throws Throwable {
    
            if(annotationLogExecutionTime.isActivate()){//Here I recover the value!!!!
                long start = System.currentTimeMillis();
                Object proceed = joinPoint.proceed();
                long executionTime = System.currentTimeMillis() - start;
                System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
                return proceed;
            }
            Object proceed = joinPoint.proceed();
            return proceed;
        }
    }
    

    Explanation:

    Our advice (logExecutionTime) will be excuted around (joinPoint) the function that will be annotated with AnnotationLogExecutionTime (our custom annotation) so I want to active or not this the calculation of time execution so I'll get the value from the membre of our custom annotation (which you ask about ;) )

    0 讨论(0)
提交回复
热议问题