Spring AOP:@annotation() 切入点与类型注解不匹配

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


之前我已经添加了 @Target(ElementType.Method) 并且我在方法上使用了这个注释并且它工作正常。现在我想把它改成@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


@RestController

@RequestMapping(value = "....", produces = { "application/json" })

@ReLogger

public class Samplecontroller {

    /** Some logic here**/.....

}

调用 API SampleController 时不打印请求


白猪掌柜的
浏览 99回答 1
1回答

一只斗牛犬

您@annotation匹配类型注释的前提是错误的,@within:将匹配限制为具有给定注释的类型内的连接点(使用 Spring AOP 时执行在具有给定注释的类型中声明的方法)。@annotation:将匹配限制为连接点的主题(在 Spring AOP 中执行的方法)具有给定注释的连接点。因此,您应该使用@within(fully.qualified.AnnotationType).
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java