Search code examples
javaspring-bootloggingjavaagentsbyte-buddy

Bytebuddy javaagent intercepting spring beans annotated with *.Controller


As the title suggests, I'm making a javaagent where the main purpose is to make a nice logger for any spring boot application; for now.

What I do at the moment is typically:

private static void install(String className, String methoName, Instrumentation instr) {
    new AgentBuilder.Default().disableClassFormatChanges()
    .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
    .type(ElementMatchers.named(className))
    .transform((builder, typeDescription, classLoader, module) -> {
        return builder.visit(Advice.to(AdviceDispatcherServlet.class).on(ElementMatchers.named(methoName)));
    }).installOn(instr);
}

Which works really well if I know the path of the class, i.e., "org.springframework.web.servlet.DispatcherServlet", and method "doDispatch".

Now I'd want to only have the advice added to types annotated with "org.springframework.web.bind.annotation.RestController" without having spring dependency in my agent; how can this be done?

I've tried

..ElementMatchers.annotationType(ElementMatchers.named("org.springframework.web.bind.annotation.RestController");

which doesn't work.


Solution

  • You can use:

    isAnnotatedWith(named("org.springframework.web.bind.annotation.RestController"))
    

    You are currently matching on a full annotation, not an annotation type.