What happens if multiple AutoConfiguration classes define the same bean?

When multiple AutoConfiguration classes attempt to create the same bean, Spring Boot resolves the conflict based on bean registration rules and conditional annotations. In most cases, auto-configurations use @ConditionalOnMissingBean to ensure a bean is created only if another bean of the same type does not already exist. This prevents accidental bean duplication and allows application-level customization.

Key Points: • Spring Boot auto-configurations typically use @ConditionalOnMissingBean to avoid creating duplicate beans. • If multiple beans with the same name are registered without conditions, a bean definition conflict may occur. • Configuration order can be controlled using @AutoConfigureBefore, @AutoConfigureAfter, and @AutoConfigureOrder.

Example: Suppose two auto-configuration classes both try to create a DataSource bean. If the first bean is already registered and the second configuration uses @ConditionalOnMissingBean, Spring skips creating the second bean.

Code Example:

@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public PaymentService paymentService() {

        return new PaymentService();
    }
}

@Configuration
public class CustomConfiguration {

    @Bean
    public PaymentService paymentService() {

        return new CustomPaymentService();
    }
}

In this scenario: • Spring first detects the custom PaymentService bean. • @ConditionalOnMissingBean evaluates to false. • The auto-configured bean is not created. • The custom bean becomes the active bean.

Possible Outcomes:

1. Using @ConditionalOnMissingBean • No conflict occurs. • Existing bean takes precedence.

2. Same Bean Name Without Conditions • Spring may throw BeanDefinitionOverrideException. • Depends on bean overriding settings.

3. Bean Overriding Enabled • The later bean registration replaces the earlier one.

Best Practice: • Use @ConditionalOnMissingBean in auto-configurations. • Provide custom beans when overriding default behavior. • Avoid relying on configuration loading order unless necessary.

Interview Tip: A concise interview answer is: In Spring Boot, multiple AutoConfiguration classes usually avoid bean conflicts through @ConditionalOnMissingBean. If a bean of the same type already exists, the auto-configured bean is skipped. Without such conditions, Spring may throw a bean definition conflict or allow overriding depending on the application's configuration.