Spring AOP:获取切入点注释的参数

时间:2011-03-12 11:36:17

标签: spring aop spring-aop

考虑我已经定义了以下方面:

@Aspect
public class SampleAspect {

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

和注释

public @interface SampleAnnotation {
    String value() default "defaultValue";
}

如果我的方面有没有办法在显示方法中读取注释SampleAnnotation的value参数?

感谢您的帮助, 埃里克

2 个答案:

答案 0 :(得分:15)

将建议签名更改为

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

您将可以访问注释中的值。

有关详细信息,请参阅docs

答案 1 :(得分:0)

下面,我将添加一个完整的AOP实现示例,其中将从“自定义” pointCut批注中获取参数,我的建议旨在计算函数的时间执行:

1-自定义注释:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationLogExecutionTime {

    public boolean isActivate() default false;

}

2-控制器:

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

3-建议

@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;
    }
}

说明:

我们的建议(logExecutionTime)将在(joinPoint)周围被取消,该函数将用AnnotationLogExecutionTime(我们的自定义注释)进行注释,所以我想激活或不激活此函数时间执行的计算,所以我将从自定义批注(您要询问的;)的值中获取值)