Sub topic 4
How auto-configuration creates beans from the classpath
This chapter assumes you know what beans, the application context and dependency injection are. It also assumes you can write @Configuration classes with @Bean methods and can run a basic Spring Boot application. The previous chapters covered starters and @SpringBootApplication. This chapter follows what happens after @EnableAutoConfiguration takes effect.
The working model
Auto-configuration is ordinary Spring Java configuration with two differences:
- Boot discovers the classes itself. You never import them.
- Almost every bean in them is guarded by a condition. A condition inspects the classpath, the existing beans, or the properties, and decides whether to create the bean.
When you add spring-boot-starter-web, you do not tell Boot to start a web server. The starter puts Tomcat, Spring MVC and Jackson on the classpath. Boot's auto-configuration classes notice those libraries and register the matching beans.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>The starter is only a dependency bundle. The decisions are made by auto-configuration classes, which mostly live in the spring-boot-autoconfigure jar. Starters bring in libraries. Auto-configuration reacts to them.
The sequence at startup
The @EnableAutoConfiguration annotation inside @SpringBootApplication imports a selector. The selector runs this sequence:
- It reads every
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsfile on the classpath. Each line names one auto-configuration class. - It merges the lists from all jars, removes duplicates, and removes any classes you excluded.
- It sorts the candidates, using ordering rules covered in a later chapter.
- It hands the candidates to Spring, which evaluates each class's conditions and registers beans only for the classes and methods whose conditions pass.
Hundreds of candidates exist in a typical application, but most are skipped. A class for Kafka does nothing when Kafka is not on the classpath. This is why a Boot application with a small dependency list stays small.
Why your beans win: the deferred import
Auto-configuration classes are processed after your own configuration classes. Boot achieves this with a deferred import selector. Spring first registers the bean definitions from your @Configuration classes and component scan. Only then does it process the auto-configuration candidates.
This ordering is what makes @ConditionalOnMissingBean reliable. When Boot's condition asks "is there already a DataSource?", your definition is already visible. If it is, the auto-configured bean backs off.
Anatomy of an auto-configuration class
Here is the example auto-configuration used throughout this tutorial:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}Each annotation does one job:
| Annotation | Role |
|---|---|
| `@AutoConfiguration` | Marks the class as an auto-configuration. It is a `@Configuration` with proxy bean methods turned off, and it supports ordering attributes such as `after` and `before`. |
| `@ConditionalOnClass` | Class-level gate. If `GreetingService` is not on the classpath, Boot skips the whole class. |
| `@EnableConfigurationProperties` | Registers `GreetingProperties` as a bean so the properties can be injected. |
| `@ConditionalOnMissingBean` | Creates the bean only if no `GreetingService` bean exists yet. |
@ConditionalOnMissingBean with no arguments uses the return type of the @Bean method. Here that is GreetingService.
The class has no proxyBeanMethods setting to tune, because @AutoConfiguration already turns proxying off. Bean methods should not call each other. Take dependencies as method parameters instead, as greetingService does with properties.
A concrete case: choosing a web server
Boot's own web server setup follows the same pattern. The servlet web server auto-configuration contains nested configuration classes, one per supported server. Each is guarded by a check for that server's classes, and each bean backs off if a ServletWebServerFactory already exists.
spring-boot-starter-webbrings inspring-boot-starter-tomcat, so Tomcat classes are present and the Tomcat factory is created.- If you exclude the Tomcat starter and add
spring-boot-starter-jetty, the Tomcat condition fails and the Jetty one passes.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>You changed no Java code. Changing the classpath changed the beans.
The nested-class rule for optional libraries
Condition annotations at the class level are evaluated by reading class metadata, not by loading the class. This lets Boot check for a class that might be missing without throwing NoClassDefFoundError.
The same safety does not extend to method signatures. If a @Bean method has a parameter or return type from an optional library, Spring may need to load that type to introspect the configuration class. When the library is absent, this fails.
The fix is to move such beans into a nested static configuration class guarded by @ConditionalOnClass:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@AutoConfiguration
public class GreetingJsonAutoConfiguration {
public static class GreetingJsonWriter {
private final ObjectMapper mapper;
public GreetingJsonWriter(ObjectMapper mapper) {
this.mapper = mapper;
}
public String write(String greeting) throws Exception {
return mapper.writeValueAsString(java.util.Map.of("greeting", greeting));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
static class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean
GreetingJsonWriter greetingJsonWriter(ObjectMapper mapper) {
return new GreetingJsonWriter(mapper);
}
}
}The outer class never mentions Jackson in a signature. The nested class is only processed when ObjectMapper is on the classpath. The ObjectMapper parameter is satisfied by Boot's own Jackson auto-configuration, which is another reason ordering matters. The ordering chapter covers it.
Common errors
- The auto-configuration never runs. The class is not listed in the imports file, or the file is in the wrong path or has a typo. The file name must be exactly
org.springframework.boot.autoconfigure.AutoConfiguration.imports, and it contains one fully qualified class name per line. - The class is component-scanned instead. Auto-configuration classes should not sit in a package your
@ComponentScancovers. If they do, they are treated as normal configuration and processed early. Conditions such as@ConditionalOnMissingBeanthen behave unpredictably. - Two beans of the same type. A condition that is too loose, such as
@ConditionalOnMissingBeanon a bean of a type you did not intend to guard, or a missing condition, leaves both your bean and the auto-configured bean in the context. Injection then fails withNoUniqueBeanDefinitionException. - A bean silently missing. A class-level condition failed. This is not an error, so no exception appears. Read the conditions report in a later chapter to see which condition failed.
- Old
spring.factoriesregistration. Before Boot 2.7, auto-configurations were registered under theEnableAutoConfigurationkey inMETA-INF/spring.factories. Boot 3 reads only the.importsfile. Libraries that target Boot 3 must use the new file.
Trade-offs
Auto-configuration saves boilerplate, but it hides decisions. A bean exists because a condition passed, and nothing in your source says so. When behavior surprises you, the cause is often a transitive dependency that added a class to the classpath. Explicit configuration of the beans you care about, plus the conditions report, keeps this manageable.
The backing-off design also means a single user-defined bean can disable a whole feature's defaults. If you define your own ObjectMapper, Boot's Jackson customizations through properties no longer apply to it. You are responsible for the configuration of beans you define yourself.
Exercise
Your application defines its own bean of type GreetingService, and the GreetingAutoConfiguration shown in this chapter is on the classpath. Which bean ends up in the context, and which mechanism causes that? What happens if you remove @ConditionalOnMissingBean from the auto-configuration method?
Show answer
Only your bean ends up in the context. Auto-configuration classes are processed after your own configuration, so your GreetingService definition is already registered when Boot evaluates @ConditionalOnMissingBean. The condition fails and the auto-configured bean is skipped. If you remove the annotation, both definitions are registered, and any injection point that asks for a single GreetingService fails with NoUniqueBeanDefinitionException unless one bean is marked @Primary or the injection point names a bean.
Exercise
Your auto-configuration has a @Bean method whose return type comes from a library that is optional. The library is missing in some applications and they fail at startup. How do you fix it?
Show answer
Move the bean into a nested static class annotated with @Configuration(proxyBeanMethods = false) and @ConditionalOnClass for the optional library's class. Class-level conditions are read from metadata without loading the class, so the nested class is skipped cleanly when the library is absent. The outer class then has no reference to the optional type in any method signature.