Conditional Annotations in Spring Boot allow beans, configurations, or components to be created only when specific conditions are satisfied. They help make applications flexible, modular, and environment-aware by enabling or disabling functionality automatically based on runtime conditions.
Suppose an application supports both MySQL and PostgreSQL databases. Based on the configuration provided by the user, Spring Boot can automatically create the appropriate database bean without changing the code.
@Configuration
public class DatabaseConfig {
@Bean
@ConditionalOnProperty(
name = "database.type",
havingValue = "mysql")
public DataSource mysqlDataSource() {
return new MysqlDataSource();
}
}database.type=mysql
The MySQL bean is created.
database.type=postgres
The bean is not created.
1. @ConditionalOnClass
@ConditionalOnClass(
DataSource.class)
2. @ConditionalOnMissingBean
@ConditionalOnMissingBean(
PaymentService.class)
3. @ConditionalOnBean
@ConditionalOnBean(
DataSource.class)
4. @ConditionalOnProperty
@ConditionalOnProperty(
name = "feature.cache.enabled",
havingValue = "true")
5. @ConditionalOnMissingClass
6. @ConditionalOnWebApplication
7. @ConditionalOnNotWebApplication
Spring Boot Auto Configuration works using conditional annotations.
The application automatically loads the correct implementation based on configuration.
A concise interview answer is: Conditional annotations in Spring Boot allow beans and configurations to be loaded only when specific conditions are met. They are widely used in Spring Boot's auto-configuration mechanism to create environment-aware and flexible applications. Common examples include @ConditionalOnClass, @ConditionalOnBean, @ConditionalOnMissingBean, and @ConditionalOnProperty.
Last updated: 11 November 2026
Previous question: How does Spring Boot simplify the data access layer implementation?