Chapter 04

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.

⏱ 20 min readLevel: intermediateCore chapter

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.

what spring-boot-starter-web actually pulls in
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
StarterBrings
…-starter-webSpring MVC, embedded Tomcat, Jackson
…-starter-webfluxReactive stack on Netty (do not combine with web)
…-starter-data-jpaHibernate, Spring Data, HikariCP, transactions
…-starter-jdbcJdbcTemplate + HikariCP, no ORM
…-starter-validationHibernate Validator (Bean Validation)
…-starter-securitySpring Security — secures everything on sight
…-starter-actuatorHealth, metrics, Micrometer
…-starter-testJUnit 5, AssertJ, Mockito, JSONassert, Spring Test
Swapping the embedded server

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

Flow from main method through @EnableAutoConfiguration, the imports file, condition filtering, and the resulting registered or skipped beans
Candidates are listed in a file, then filtered by conditions. Nothing more.
  1. 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 used spring.factories; you will still see that in older articles.)
  2. Candidates are ordered @AutoConfigureBefore, @AutoConfigureAfter and @AutoConfigureOrder decide who gets to look at the context first.
  3. Conditions are evaluated Class-level conditions first (cheap, based on classpath scanning), then method-level.
  4. Surviving beans are registered And crucially — this happens after your own configuration, which is what makes @ConditionalOnMissingBean work.

The conditional annotations

AnnotationMatches when
@ConditionalOnClassA class is on the classpath
@ConditionalOnMissingClassA class is absent
@ConditionalOnBeanA bean of that type already exists
@ConditionalOnMissingBeanNo such bean exists — the back-off mechanism
@ConditionalOnPropertyA property has a given value
@ConditionalOnResourceA file exists on the classpath
@ConditionalOnWebApplicationServlet or reactive web app
@ConditionalOnExpressionA SpEL expression is true
@ConditionalOnThreadingPlatform vs virtual threads (Boot 3.2+)

A real auto-configuration, simplified

JacksonAutoConfiguration (abridged)
@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.

application.yml
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.

a customizer bean
@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.

full replacement
@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

two equivalent ways
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class BookstoreApplication { }
application.yml
spring:
  autoconfigure:
    exclude:
      - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
      - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Excluding is usually the wrong fix

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:

terminal
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug
# or
java -jar target/bookstore.jar --debug
CONDITIONS EVALUATION REPORT (abridged)
============================
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
How to use it

"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:

application.yml
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.

AuditProperties.java
@ConfigurationProperties(prefix = "bitsnippets.audit")
public record AuditProperties(
        @DefaultValue("true")  boolean enabled,
        @DefaultValue("audit") String  topic,
        @DefaultValue("100")   int     batchSize) { }
AuditAutoConfiguration.java
@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);
    }
}
src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.bitsnippets.audit.AuditAutoConfiguration
Three rules for a good starter

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

AuditAutoConfigurationTest.java
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".