How to use byte-buddy in springboot

Viewed 346

I want to use byte-buddy to intercept methods with java annotation. A simplified example is as follows:

  • Annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TraceLog {
    String logName() default "";
}
  • The Interceptor class is
public class TraceLogInterceptor {
    @RuntimeType
    public static Object handleTraceLog(@Origin Method method,
                                        @AllArguments Object[] args,
                                        @SuperCall Callable<?> superCall) throws Exception {
         TraceLog traceLogAnnotation = method.getAnnotation(TraceLog.class);
         System.out.println(traceLogAnnotation.logName());
         superCall.call();
    }
}
  • The service class is
public class HelloServiceImpl {
    @TraceLog(logName = "myLog")
    public String writeHello(String name) {
        return "Hello " + name;
    }
}
  • The test method is
 @Test
    public void writeHello() throws IllegalAccessException, InstantiationException, IOException, NoSuchMethodException, InvocationTargetException {
        DynamicType.Unloaded<?> dynamicType =
                new ByteBuddy()
                        .subclass(HelloServiceImpl.class)
                        .method(ElementMatchers.isAnnotatedWith(TraceLog.class))
                        .intercept(MethodDelegation.to(TraceLogInterceptor.class))
                        .make();

        HelloServiceImpl helloService = (HelloServiceImpl) dynamicType.load(this.getClass().getClassLoader())
                .getLoaded()
                .getConstructor()
                .newInstance();
        System.out.println(helloService.writeHello("XXXXX"));
    }

It can work. However, I want to know how to inject the interceptor(TraceLogInterceptor) to spring. And I also want to know how to intercept all methods with the @TraceLog annotation and generate the corresponding proxy class without specifying the superclass(new ByteBuddy().subclass(xxx)). Thanks!

0 Answers
Related