Hello, I saw the different issues https://github.com/spring-projects/spring-boot/issues/45938 and https://github.com/spring-projects/spring-boot/issues/45709
The issue here is different from those. I set up a really stupid example that is not our use-case, but it illustrates the goal.
Consider a class GenericClass<T>
.
Working in 3.4.6 :
@Bean
public GenericClass<String> genericBean1() {
return new GenericClass<>("Hello, Generics!");
}
@Bean
@ConditionalOnMissingBean
public GenericClass<Integer> genericBean2() {
return new GenericClass<>(7);
}
@Bean
public CommandLineRunner init(GenericClass<?> genericBean) {
return args -> System.out.println("GenericClass with value: " + genericBean.getValue());
}
Starting from 3.5.0 :
Parameter 0 of method init in com.example.generics.demo.DemoApplication required a single bean, but 2 were found:
- genericBean1: defined by method 'genericBean1' in class path resource [com/example/generics/demo/DemoConfiguration.class]
- genericBean2: defined by method 'genericBean2' in class path resource [com/example/generics/demo/DemoConfiguration2.class]
The only "workaround" in 3.5+ is to change the bean definitions with the wildcard ?
instead of the concrete type.
For example :
@Bean
@ConditionalOnMissingBean
public GenericClass<?> genericBean2() {
return new GenericClass<>(7);
}
I have not seen anything regarding this in the changelog.
Is it still possible to define @ConditionalOnMissingBean
with a type that uses Generics where the concrete type used in the generic might defer ?
Comment From: wilkinsona
Have you tried @ConditionalOnMissingBean(GenericClass.class)
?
Comment From: vmeunier
Nope, and it works if I add it
It gives a way easier "workaround" if I simply add that instead of using wildcards.
Comment From: wilkinsona
Thanks for trying it. This is then working as designed. There's a very brief mention of this change in the miscellaneous section of the release notes for 3.5, but I think they'd benefit from a dedicated section with some examples. We can use this issue to add such a section.
Comment From: vmeunier
Thanks for the information !
I agree it would be worth mentionning that @ConditionalOnMissingBean
on a generic type will by default check the generics, and if you don't care about the actual type you can specify the GenericClass directly in the condition. (which was the default behaviour in SpringBoot 3.4-)