the_way
the_way

Reputation: 181

Spring AOP: @annotation() pointcut does not match type annotation

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)

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

Using @ReLoggerAspect on a class

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

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

Upvotes: 2

Views: 1937

Answers (1)

kriegaex
kriegaex

Reputation: 67297

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: 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: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.

Thus, you ought to use @within(fully.qualified.AnnotationType).

Upvotes: 5

Related Questions