Auto-configuration and starters
The "magic" of Spring Boot is a few hundred @Configuration classes with
if statements attached. Once you can read them, the framework stops being
mysterious and starts being predictable.
Starters: curated dependency sets
A starter is a pom with no code in it. Its entire job is to depend on a coherent set of libraries at versions known to work together.
spring-boot-starter-web ├── spring-boot-starter core: logging, autoconfigure, spring-core ├── spring-boot-starter-json jackson-databind + jsr310 + parameter-names ├── spring-boot-starter-tomcat embedded Tomcat ├── spring-web RestClient, HTTP abstractions └── spring-webmvc DispatcherServlet, @Controller support
| Starter | Brings |
|---|---|
…-starter-web | Spring MVC, embedded Tomcat, Jackson |
…-starter-webflux | Reactive stack on Netty (do not combine with web) |
…-starter-data-jpa | Hibernate, Spring Data, HikariCP, transactions |
…-starter-jdbc | JdbcTemplate + HikariCP, no ORM |
…-starter-validation | Hibernate Validator (Bean Validation) |
…-starter-security | Spring Security — secures everything on sight |
…-starter-actuator | Health, metrics, Micrometer |
…-starter-test | JUnit 5, AssertJ, Mockito, JSONassert, Spring Test |
Exclude Tomcat from the web starter and add Undertow or Jetty. Nothing in your code changes — the auto-configuration picks whichever server class it finds.
<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-undertow</artifactId>
</dependency>
How auto-configuration resolves
-
The imports file is read
Every jar can contribute
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports— a plain list of class names. (Boot 2 usedspring.factories; you will still see that in older articles.) -
Candidates are ordered
@AutoConfigureBefore,@AutoConfigureAfterand@AutoConfigureOrderdecide who gets to look at the context first. - Conditions are evaluated Class-level conditions first (cheap, based on classpath scanning), then method-level.
-
Surviving beans are registered
And crucially — this happens after your own configuration, which is what makes
@ConditionalOnMissingBeanwork.
The conditional annotations
| Annotation | Matches when |
|---|---|
@ConditionalOnClass | A class is on the classpath |
@ConditionalOnMissingClass | A class is absent |
@ConditionalOnBean | A bean of that type already exists |
@ConditionalOnMissingBean | No such bean exists — the back-off mechanism |
@ConditionalOnProperty | A property has a given value |
@ConditionalOnResource | A file exists on the classpath |
@ConditionalOnWebApplication | Servlet or reactive web app |
@ConditionalOnExpression | A SpEL expression is true |
@ConditionalOnThreading | Platform vs virtual threads (Boot 3.2+) |
A real auto-configuration, simplified
@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class) // jackson-databind present?
public class JacksonAutoConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean // did the user define one?
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
@Bean
@ConditionalOnMissingBean
Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
customizers.forEach(c -> c.customize(builder));
return builder;
}
}
That is the whole pattern. Every one of the ~150 auto-configurations looks like this.
Three ways to override a default
Ranked from least to most invasive — always prefer the earlier option.
spring:
jackson:
default-property-inclusion: non_null
serialization:
write-dates-as-timestamps: false
indent-output: false
deserialization:
fail-on-unknown-properties: true
Most auto-configurations are driven by @ConfigurationProperties. Check for a
property before writing any Java — there usually is one.
@Bean
Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> builder
.serializationInclusion(JsonInclude.Include.NON_NULL)
.modulesToInstall(new MoneyModule())
.simpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
}
You adjust the auto-configured object instead of replacing it, so you keep every other
default. Boot offers *Customizer hooks for Jackson, Tomcat, RestClient,
Micrometer and more.
@Bean
ObjectMapper objectMapper() {
// The auto-configured one now backs off entirely, because of
// @ConditionalOnMissingBean. You own every setting from here on.
return JsonMapper.builder()
.addModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.serializationInclusion(JsonInclude.Include.NON_NULL)
.build();
}
Total control, and you silently lose every default Boot would have applied. Reach for this last.
Excluding an auto-configuration
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class BookstoreApplication { }
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
- org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Excluding SecurityAutoConfiguration to escape a 401 disables security
entirely. Excluding DataSourceAutoConfiguration to avoid a startup failure
just moves the failure to first use. Excluding is right when a starter arrives
transitively and you genuinely do not want the feature — otherwise, configure it.
Debugging: the condition evaluation report
The single most useful diagnostic in Spring Boot. Run with --debug:
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug # or java -jar target/bookstore.jar --debug
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches:
-----------------
DataSourceAutoConfiguration matched:
- @ConditionalOnClass found required classes 'javax.sql.DataSource' (OnClassCondition)
DataSourceAutoConfiguration#Hikari matched:
- @ConditionalOnMissingBean (types: javax.sql.DataSource) did not find any beans
Negative matches:
-----------------
RedisAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class
'org.springframework.data.redis.core.RedisOperations' (OnClassCondition)
SecurityAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class
'org.springframework.security.authentication.DefaultAuthenticationEventPublisher'
Exclusions:
-----------
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
"Feature X is not working" → search the report for X's auto-configuration in Negative matches. The reason is stated in one line: a missing class (add the dependency), an existing bean (you already defined one), or a property (switch it on). This turns a two-hour hunt into a thirty-second lookup.
The same data is available as JSON while the app runs:
management:
endpoints:
web:
exposure:
include: conditions,beans,configprops,env
Writing your own auto-configuration
Worth doing once you have three services copying the same @Configuration class.
The convention is two modules: an -autoconfigure module with the code, and a
-starter module that is just dependencies.
@ConfigurationProperties(prefix = "bitsnippets.audit")
public record AuditProperties(
@DefaultValue("true") boolean enabled,
@DefaultValue("audit") String topic,
@DefaultValue("100") int batchSize) { }
@AutoConfiguration
@ConditionalOnClass(AuditPublisher.class)
@ConditionalOnProperty(prefix = "bitsnippets.audit",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {
@Bean
@ConditionalOnMissingBean // always allow the user to override
AuditPublisher auditPublisher(AuditProperties properties) {
return new KafkaAuditPublisher(properties.topic(), properties.batchSize());
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnWebApplication(type = Type.SERVLET)
AuditFilter auditFilter(AuditPublisher publisher) {
return new AuditFilter(publisher);
}
}
com.bitsnippets.audit.AuditAutoConfiguration
1. Never use @ComponentScan in an auto-configuration — it
would scan the consumer's packages unpredictably. Declare beans explicitly.
2. Put @ConditionalOnMissingBean on every bean, so consumers
can always override.
3. Name it xxx-spring-boot-starter, never
spring-boot-starter-xxx — that prefix is reserved for the Spring team.
Testing an auto-configuration
class AuditAutoConfigurationTest {
private final ApplicationContextRunner runner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class));
@Test
void registersPublisherByDefault() {
runner.run(context -> assertThat(context).hasSingleBean(AuditPublisher.class));
}
@Test
void backsOffWhenDisabled() {
runner.withPropertyValues("bitsnippets.audit.enabled=false")
.run(context -> assertThat(context).doesNotHaveBean(AuditPublisher.class));
}
@Test
void userBeanWins() {
runner.withUserConfiguration(CustomPublisherConfig.class)
.run(context -> assertThat(context).getBean(AuditPublisher.class)
.isInstanceOf(NoopAuditPublisher.class));
}
}
ApplicationContextRunner builds a real but tiny context per assertion, in
milliseconds. It is the correct tool here — far better than @SpringBootTest.
You define your own DataSource bean. What happens to Boot's?
Auto-configurations are processed after user configuration precisely so that
@ConditionalOnMissingBean can see your beans and stand down. That ordering is
the whole basis of "sensible defaults that you can always override".