Spring AOP:@annotation()切入点与类型注释不匹配 [英] Spring AOP: @annotation() pointcut does not match type annotation

查看:43
本文介绍了Spring AOP:@annotation()切入点与类型注释不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个方面来记录控制器中每个API调用的请求和响应.我希望能够在类上使用此批注,因此使用了@Target(ElementType.TYPE)

I'm writing an aspect to log Request and Response of each API call in a controller. I want to be able to use this annotation on a class, hence used @Target(ElementType.TYPE)

以前,我已经添加了@Target(ElementType.Method),并且在方法上使用了此批注,并且运行良好.现在,我想将其更改为@Target(ElementType.TYPE)

Previously I had added @Target(ElementType.Method) and I was using this annotation on methods and it was working fine. Now I want to change it to @Target(ElementType.TYPE)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReLogger {}

@Aspect
@Component
public class ReLoggerAspect {
    public static final Logger log = LoggerFactory.getLogger("ReLoggerAspect");

    @PostConstruct
    private void postConstruct() {
        log.info("ReLoggerAspect Created");
    }

    @Around("@annotation(ReLogger)")
    private Object reqLoggingAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("Request {}",jointPoint.getArgs()[0);
    }
}

在类上使用@ReLoggerAspect

Using @ReLoggerAspect on a class

@RestController
@RequestMapping(value = "....", produces = { "application/json" })
@ReLogger
public class Samplecontroller {
    /** Some logic here**/.....
}

在调用API SampleController时不会打印请求

It doesn't print the Request when an API SampleController is invoked

推荐答案

您使 @annotation 与类型注释匹配的前提是错误的,请参阅(Spring AOP手册](

Your premise that @annotation would match type annotations is wrong, see (Spring AOP manual](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators):

  • @within :将匹配限制为具有给定注释的类型内的连接点(使用Spring AOP时,使用给定注释的类型中声明的方法的执行).

  • @within: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP).

@annotation :将匹配点限制为连接点的主题(在Spring AOP中执行的方法)具有给定注释的连接点.

@annotation: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.

因此,您应该使用 @within(fully.qualified.AnnotationType).

这篇关于Spring AOP:@annotation()切入点与类型注释不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆