How do you make a Spring Boot auto-configuration back away when a bean already exists?

Spring Boot auto-configuration is designed to provide default beans automatically. However, if a developer defines a custom bean of the same type, the auto-configuration should "back away" and allow the custom bean to take precedence. This behavior is commonly achieved using the @ConditionalOnMissingBean annotation.

Key Points

Example

Suppose Spring Boot provides a default EmailService bean. If the application developer creates a custom EmailService bean, Spring Boot should not create the default bean again.

@Configuration
public class EmailAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(
            EmailService.class)
    public EmailService emailService() {

        return new DefaultEmailService();
    }
}

Custom Bean

@Configuration
public class CustomConfig {

    @Bean
    public EmailService emailService() {

        return new CustomEmailService();
    }
}

Result

How It Works

Application Startup

↓

Check Existing Beans

↓

EmailService Exists?

/ \

Yes No

↓ ↓

Skip Bean Create Bean

Common Conditional Annotations Used in Auto-Configuration

Real-World Example

Spring Boot DataSource Auto-Configuration

@Configuration
public class DataSourceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(
            DataSource.class)
    public DataSource dataSource() {

        // Default DataSource
    }
}

If the developer defines

@Bean
public DataSource customDataSource() {

    return new HikariDataSource();
}

Spring Boot will not create its default DataSource because a custom one already exists.

Benefits

Best Practice

When creating custom Spring Boot starters or auto-configurations, use @ConditionalOnMissingBean to provide sensible defaults while still allowing developers to override them easily.

Interview Tip

A concise interview answer is: To make an auto-configuration back away when a bean already exists, Spring Boot uses the @ConditionalOnMissingBean annotation. It tells Spring to create the bean only if no bean of the specified type is present in the application context. This allows developers to provide custom implementations while preventing conflicts with default auto-configured beans.

Last updated: 11 November 2026

Previous question: You need to secure a Spring Boot application to ensure that only authenticated users can access certain endpoints. Describe how you would configure Spring Security to set up a basic form-based authentication.

Next question: How do you deploy a Spring Boot web application as a JAR or WAR file?

More Spring Boot - Level II interview questions

All Spring Boot - Level II questions