Java and Spring Level 3 This level · 38 of 56
Hard java spring

How does Spring Boot decide which auto-configuration to apply?

The 30 second answer

Spring Boot uses AutoConfigurationImportSelector to load potential auto-configurations from the libraries on the classpath. It removes duplicates and exclusions, then filters out candidates that fail early checks such as @ConditionalOnClass. The remaining configurations are processed in the appropriate order, with bean-level conditions deciding what actually gets created. Where @ConditionalOnMissingBean applies, defining your own bean makes the corresponding default back off.

Could you say this in an interview?

Spring Boot does not scan every jar for @Configuration classes and guess. The process is explicit.

@SpringBootApplication includes @EnableAutoConfiguration, and that annotation imports AutoConfigurationImportSelector. The selector loads candidates with ImportCandidates, which reads one .imports file per jar:

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

The selection logic in Spring Boot's source is short:

List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);

AutoConfigurationImportSelector.java L130-L143

The decision happens in two stages.

Stage 1: candidate filtering. Class-level conditions such as @ConditionalOnClass, @ConditionalOnWebApplication and @ConditionalOnProperty can reject a whole auto-configuration. If Tomcat is not on the classpath, the Tomcat auto-configuration is dropped before any of its beans are considered.

Stage 2: bean creation. Surviving classes are processed like normal configuration classes during context refresh. Each @Bean method can carry its own condition. The most common one is @ConditionalOnMissingBean: if the application already defines a bean of that type, Spring Boot skips its default.

@Bean
DataSource dataSource() {
    return DataSourceBuilder.create()
            .url("jdbc:postgresql://localhost/orders")
            .username("orders").password("secret")
            .build();
}

With this bean in place, Spring Boot's own DataSource auto-configuration backs off.

Auto-configurations are also ordered with @AutoConfiguration(before = ..., after = ...), so a configuration that checks for a bean runs after the one that may create it. That is why the docs say @ConditionalOnMissingBean should only be used in auto-configuration classes, where the order is controlled.

To see what happened, run the app with --debug. Spring Boot prints a condition evaluation report with positive matches, negative matches, exclusions and unconditional classes.

Interview distinction: the .imports file only lists candidates. Conditions decide what takes effect. And "my bean always wins" is not a universal rule; it works because most defaults are guarded by @ConditionalOnMissingBean.

Alternate interview scenarios

"Some beans fail to initialize in production but work in development. How do you investigate conditional bean registration?"

Auto-configuration is decided by conditions, so I ask Spring Boot why it made each decision. Running with --debug, or enabling DEBUG logging, prints the condition evaluation report, which lists positive and negative matches with the reason for each. With Actuator, the conditions endpoint shows the same report on a running instance. Then I compare what differs between the environments. Check the active profiles and @ConditionalOnProperty values from environment variables, the classpath, because a test-scoped or optional dependency may be missing in the production artifact, and @ConditionalOnMissingBean order, where a bean defined in production config backs off an auto-configured one. For a bean that exists but fails to start, I read the failure analysis printed at startup.

"How would you test a conditional bean configuration?"

This is a test-design question, not a production investigation. I do not boot the whole application. I use ApplicationContextRunner with the auto-configuration or @Configuration under test, then I vary the classpath (withClassLoader or FilteredClassLoader) and properties (withPropertyValues, including spring.profiles.active when a profile matters) and assert that a bean is present or absent with hasSingleBean or doesNotHaveBean (or hasFailed when a condition should stop the context). I include the conflict case, where my own @Bean should make @ConditionalOnMissingBean back off, and the missing-property case, where @ConditionalOnProperty should not match. @SpringBootTest with properties and an active profile is the coarser alternative when I need the full slice. The condition evaluation report (--debug or the conditions endpoint) explains a failure; it is not a substitute for those assertions.

Sources (7)
  1. Spring Boot reference: Testing your auto-configuration (`ApplicationContextRunner`)docs.spring.io
  2. Spring Boot reference: Testing Spring Boot applications (`@SpringBootTest`)docs.spring.io
  3. Spring Boot API: ApplicationContextAssert (`hasSingleBean`, `doesNotHaveBean`, `hasFailed`)docs.spring.io
  4. Spring Boot reference: Creating your own auto-configuration (locating candidates, condition annotations)docs.spring.io
  5. Spring Boot reference: Using auto-configurationdocs.spring.io
  6. ImportCandidates.load L69-L79github.com
  7. Spring Boot how-to: Troubleshoot auto-configuration (ConditionEvaluationReport)docs.spring.io
Previous
Next