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

31

假设我定义了以下切面:

@Aspect
public class SampleAspect {

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

还有注释

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

如果我的方面存在,有没有一种方法可以在显示方法中读取注释SampleAnnotation的值参数?

感谢您的帮助, erik


2
可能是访问通知中的注释值的重复问题。 - axtavt
3个回答

49
将建议签名更改为:
@Around(value="@annotation(sampleAnnotation)")
public Object display(ProceedingJoinPoint joinPoint, SampleAnnotation sampleAnnotation ) throws Throwable {
    // ...
}

你将能够访问注释中的值。

有关更多信息,请参见docs


2
有关详细文档,请查看:http://docs.spring.io/spring/docs/3.0.3.RELEASE/spring-framework-reference/html/aop.html - 第7.2.4.6节建议参数。 - hoodieman
8
这里的微妙差别在于 @Around 值必须包含一个 参数名称 而不是注解的名称。在这个答案中它们几乎相同(唯一的区别只是首字母的大小写),所以一开始我很困惑为什么我的代码不起作用,直到我注意到了字母的大小写。 - Ruslan Stelmachenko

8
以下是一个完整的AOP实现示例,其中我将从我的自定义pointCut注释中获取参数,我的advice旨在计算函数执行的时间:
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)将在被注解为AnnotationLogExecutionTime(我们自定义的注解)的函数周围(joinPoint)执行,因此我想激活或不激活执行时间的计算,因此我将从自定义注解的成员中获取值(你所询问的;))


0

之前我对于如何进行映射感到困惑。

@Before("@annotation(any_variable_name) && args(spring_will_find_its_type_to_match)")
public void myAdvice(JoinPoint joinPoint, MyAnnotation any_variable_name, MyClass spring_will_find_its_type_to_match) {
    System.out.println("before testing in Aspect myAdvice " + spring_will_find_its_type_to_match);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接