Now I'm developing spring starter libraries, and suddenly I feel like @ConditionalOnMissingBean
is misused in my code. Assumes that there are two auto-configuration classes.
@Configuration
public class ProviderAutoConfiguration {
@Bean
@Primary
public Component component() {
return new Component();
}
}
@Configuration
@AutoConfigureAfter(ProviderAutoConfiguration.class)
public class ConsumerAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Component fallback() {
return Component.NOOP;
}
@Bean
public Consumer consumer(Component component) {
return new Consumer(component);
}
}
The scenario is these two auto-configuration classes are in different libraries, users may only import the consumer library. So if I use @ConditionalOnMissingBean
, the ConsumerAutoConfiguration
will register a fallback bean to ApplicationContext
. This behavior may cause other problems.
@Configuration
public class OtherProviderAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Component thirdParty() {
return new Component();
}
}
Assumes that users import another library which is developed by others. Now nobody knows the behavior of Component
bean initialization.
@Configuration
public class ConsumerAutoConfiguration {
@Autowired(required = false)
private Component component = Component.NOOP;
@Bean
public Consumer consumer() {
return new Consumer(component);
}
}
So my question is should I use @Autowired
instead of @ConditionalOnMissingBean
in this kind of scenario? Or is there a better way than both of them?