Search code examples
javaspring-bootbyte-buddy

Using ByteBuddy to generate Spring Boot configuration


I'm trying to generate Spring Boot configuration code in order to solve this question. This is what I've got so far:

//@Configuration <- trying to add this through BB
public class GeneratedConfigBase {
  @Bean
  public Object hello() {
    System.out.println("hello");
    return new Object();
  }
}

@SpringBootApplication
public class TestApp {
  public static void main(String[] args) throws Exception {
    generateConf();
    SpringApplication.run(TestApp.class, args);
  }

  private static void generateConf() {
    new ByteBuddy()
        .subclass(GeneratedConfigBase.class)
        .name("com.example.GeneratedConfig")
        .annotateType(AnnotationDescription.Builder.ofType(Configuration.class).build())
        .make()
        .load(TestApp.class.getClassLoader(), ClassLoadingStrategy.UsingLookup.of(
            MethodHandles.privateLookupIn(GeneratedConfigBase.class, MethodHandles.lookup()
        ));
  }
}

The above won't print "hello" when running the app. I'm not at all sure about the load() part, but Spring Boot may not pick up the configuration for any number of reasons. Any insight would be appreciated.


Solution

  • Spring scans the class path by iterating over class files. Your generated class will not be visible via these scans, it does not have a class file representation.

    To make your class visible, you'd need to register it explicitly. I thibk Spring offers a builder for this purpose where you currently run a single main class.