What are @ConditionalOnBean and @ConditionalOnMissingBean annotations in Spring Boot?

In Spring Boot, conditional annotations enable you to configure your application based on the presence or absence of specific beans in the ApplicationContext. Two of these annotations are @ConditionalOnBean and @ConditionalOnMissingBean. Let’s discuss each of these in detail.

@ConditionalOnBean

@ConditionalOnBean is an annotation used to conditionally enable or based on the presence of specific bean in the ApplicationContext. It’s useful when you want to create beans that depend on other beans.

Usage

@Configuration
public class ExampleConfiguration {
    
    @Bean
    @ConditionalOnBean(DataSource.class)
    public ExampleService exampleService(DataSource dataSource) {
        return new ExampleService(dataSource);
    }
}

In the example above, the exampleService bean will only be created if a bean of type DataSource is present in the ApplicationContext.

@ConditionalOnMissingBean

@ConditionalOnMissingBean is the opposite of @ConditionalOnBean. This is useful in scenarios where you want to provide a default or fallback bean in the absence of a particular bean.

Usage

@Configuration
public class FallbackConfiguration {

    @Bean
    @ConditionalOnMissingBean(ExampleService.class)
    public ExampleService defaultExampleService() {
        return new DefaultExampleService();
    }
}

In the example above, the defaultExampleService bean will only be created if a bean of type ExampleService is not present in the ApplicationContext.

Pass more than one bean

To define more than one beans, pass an array of bean types to the value attribute or the name attribute of the annotations, e.g.

<pre>
@Configuration
public class ExampleConfiguration {

    @Bean
    @ConditionalOnBean(value = {DataSource.class, AnotherDependency.class})
    public ExampleService exampleService(DataSource dataSource, AnotherDependency anotherDependency) {
        return new ExampleService(dataSource, anotherDependency);
    }
}

In the example above, the exampleService bean will only be created if beans of type DataSource and AnotherDependency are present in the ApplicationContext.

Speak Your Mind