Register Spring Boot Configuration class, with generics, programmatically?

124 Views Asked by At

I have a configuration class that requires a generic configuration class defined like this in Spring Boot 3.2:

@Configuration
public class MyConfig<T> {
  
   @Bean
   public MyThing<T> myThing() {
      new MyThing<T>();
   }

   @Bean
   public MyOtherThing<T> myThingOther() {
      new MyOtherThing<T>();
   }

}

Since MyConfig takes a generic type, T, I've tried registering the class like this:

@Configuration
public class SomeConfiguration implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Class<?> type = Class.forName("org.something.SomeThing");

        Class<?> myConfig = GenericTypeResolver.resolveTypeArgument(MyConfig.class, type);
        GenericBeanDefinition definition = new GenericBeanDefinition();
        definition.setBeanClass(myConfig);
        registry.registerBeanDefinition("myConfig", definition);
    }
}

But this doesn't seem to work, no beans of type MyThing<T> or MyOtherThing<T> are created (the methods in MyConfig<T> are never called). So my question is, how can I programmatically register the MyConfig class so that the beans are created?

Update:

You can see the actual code that I work with by doing:

  1. Clone my github repo: git clone [email protected]:johanhaleby/occurrent.git (or gh repo clone johanhaleby/occurrent)
  2. And then change branch to experiment/spring-boot-annotation: git checkout experiment/spring-boot-annotation
  3. Run the org.occurrent.example.domain.rps.decidermodel.web.TestBootstrap class

The configuration that I want to load is org.occurrent.springboot.mongo.blocking.OccurrentMongoAutoConfiguration, and I try to load it from org.occurrent.springboot.mongo.blocking.OccurrentMongoRegistrar (which is triggered by annotation the @EnableOccurrent annotation used in org.occurrent.example.domain.rps.decidermodel.web.Bootstrap class).

0

There are 0 best solutions below