Search code examples
javaspringspring-bootspring-aop

How do I prevent Spring Boot AOP from removing type annotations?


I am pretty new to Spring Boot and its flavor of AOP, but not new to programming in other languages and AOP frameworks. This one challenge I am not sure how to solve.

I have a simple metadata decorator:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GreetingsMeta {
    public float version() default 0;
    public String name() default "";
}

It works just fine with dependency injection:

public GreetingController(List<IGreetingService> greetings) throws Exception {
    this.greetings = new HashMap<>();
    greetings.forEach(m -> {
        Class<?> clazz = m.getClass();
        if (clazz.isAnnotationPresent(GreetingsMeta.class)) {
            GreetingsMeta[] s = clazz.getAnnotationsByType(GreetingsMeta.class);
            this.greetings.put(s[0].name(), m);
        }
    });
}

Until I applied a standard logging aspect:

@Aspect
@Component
public class LoggingAspect {
    @Around("execution(* com.firm..*(..)))")
    public Object profileAllMethods(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName = methodSignature.getName();
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = joinPoint.proceed();
        stopWatch.stop();
        LogManager.getLogger(methodSignature.getDeclaringType())
        .info(methodName + " " + (stopWatch.getTotalTimeSeconds() * 1000) + " µs");
        return result;
    }
}

Then the list of annotationsData becomes empty, even the @Component annotation is gone.

Sample meta-decorated class:

@Component
@GreetingsMeta(name = "Default", version = 1.0f)
public class DefaultGreetingsService implements IGreetingService {


    @Override
    public String message(String content) {
        return "Hello, " + content;
    }
} 

How should I troubleshoot?


Solution

  • You may want to look into AnnotationUtils

    Method method = methodSignature.getMethod();
    GreetingsMeta greetingsMeta = AnnotationUtils.findAnnotation(method, GreetingsMeta.class);