Override @override with AOP

429 views Asked by At

I'm giving AOP a try for the first time. I want to do AOP on the @Override notation to write logs. It seems to be almost working but:

  1. I have to import my own Override class in every class. Is this normal? I thought that it would magically go through my @Override decorator first and then through the Java one.
  2. I have this very weird behavior where depending on the endpoint that I call first, it keeps working after or it only works for this one endpoint. Say, I have /a and /b, if I call /b first, it shows my logs, then I'll call /a and it won't show anything, if after that I call /b it will show logs. However, if I call /a first, it works, then I call /b and it works, and it just keeps working for all of them. It makes no sense to me.

This is my OverrideInterceptor:

@Slf4j
public class OverrideInterceptor implements MethodInterceptor<Object, Object> {

  @Override
  public Object intercept(MethodInvocationContext<Object, Object> context) {
    String prettyMethod = context.getDeclaringType().getSimpleName() + "." + context.getName();
    log.debug("{} with params {}", prettyMethod, context.getParameterValueMap());
    long start = System.nanoTime();
    Object result = context.proceed();
    long end = System.nanoTime() - start;
    log.debug("Execution of " + prettyMethod + " took: " + (end/1000) + "ms.");
    return result;
  }
}

And my annotation:

@Documented
@Retention(RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Around
@Type(OverrideInterceptor.class)
public @interface Override {

}

Both classes are in the package: package com.time.infrastructure.config;

And I'm using this @Override annotation in packages under com.time.infrastructure.db, com.time.infrastructure.rest, com.time.application.repository, etc.

1

There are 1 answers

5
ollitietavainen On BEST ANSWER

For point 1: The built-in @Override annotation is a normal @interface - it resides in the java.lang package. What you've done here is that you've created a custom annotation with the name Override in the package com.time.infrastructure.config, which has nothing to do with java.lang.Override. So in that sense, it's "normal", but it's probably not doing what you think. You can't subtype annotations in Java, unfortunately.