0

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?

Lynx
  • 23
  • 4
  • Hi! `@ConditionalOnMissingBean` is used for conditional bean initialization, you can have a look at [this](https://stackoverflow.com/a/56903971/14394219) thread. While `@Autowired` is used for bean injection, a nice answer can be found [here](https://stackoverflow.com/a/19419296/14394219) – artiomi Nov 15 '22 at 08:30
  • @artiomi Yes I know that. My point is can I use `@ConditionalOnMissingBean` to provide fallback bean? – Lynx Nov 15 '22 at 09:29
  • @artiomi I have edited title to make question easier to understand – Lynx Nov 15 '22 at 09:31

0 Answers0