【问题标题】:Spring AOP: @annotation() pointcut does not match type annotationSpring AOP:@annotation() 切入点与类型注释不匹配
【发布时间】:2019-08-06 05:21:03
【问题描述】:

我正在编写一个方面来记录控制器中每个 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 时不打印请求

【问题讨论】:

    标签: java annotations aspectj spring-aop pointcut


    【解决方案1】:

    您认为@annotation 将匹配类型注释的前提是错误的,请参阅(Spring AOP 手册](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators):

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

    • @annotation:限制匹配到连接点的主体(在 Spring AOP 中执行的方法)具有给定注解的连接点。

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

    【讨论】:

    • 哦..好的。知道了。 @within(fully.qualified.AnnotationType) 这行得通。谢谢
    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多