Auto-configuration

Key idea
Auto-configurations are ordinary `@Configuration` classes, listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`, whose beans are only created if some conditions hold (`@ConditionalOnClass`, `@ConditionalOnMissingBean`, `@ConditionalOnProperty`…). That's how Boot configures the usual things and steps aside as soon as you declare your own.
In the box
Every box app copied the same class to set up the scoreboard. Turn it into an auto-configuration that Spring Boot discovers on its own, that switches on according to the classpath and properties, that steps aside if the app brings its own bean, and that you can inspect, exclude and test.
ApplicationContextCopyPastedScoreboardConfigConsoleScoreboardScoreboardController

CopyPastedScoreboardConfig, highlighted in red, always creates ConsoleScoreboard and ScoreboardController.

@EnableAutoConfiguration reads the AutoConfiguration.imports file, which points to ScoreboardAutoConfiguration; both are highlighted.

ScoreboardAutoConfiguration asks for the conditions, highlighted, to be evaluated; since they hold, ConsoleScoreboard is created.

Your own Scoreboard, highlighted, reaches the conditions: since one already exists, the auto-configuration doesn't create its own.

The classpath, highlighted, says DispatcherServlet is there but JdbcTemplate isn't: ScoreboardController is created and JdbcScoreboard is skipped.

ScoreboardAutoConfiguration and the conditions, highlighted, are evaluated in a small context for each test case.

ScoreboardAutoConfiguration sends the condition report, highlighted, its positive and negative matches.

The spring.autoconfigure.exclude property reaches ScoreboardAutoConfiguration, highlighted, and the application starts without it.

Final view: discovery on top, the conditions in the middle fed by the classpath and your beans, and the resulting beans at the bottom.

Step 1 of 9

The same class copied into every app

The box scoreboard (Scoreboard) is used by several applications. Each one copied CopyPastedScoreboardConfig:

  • It always creates the scoreboard, with a hard-coded title.
  • It always creates the web controller, even in apps without a web layer.
  • If an app wants its own scoreboard, it has to delete or edit the copied class.

Step 2 of 9

How Boot finds auto-configurations

@SpringBootApplication includes @EnableAutoConfiguration, which:

  1. Reads, from every jar on the classpath, the file META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.
  2. Each line is a candidate class. This module brings its own:
com.spring2learn.box.autoconfig.scoreboard.ScoreboardAutoConfiguration
  1. Evaluates their conditions and registers the beans that pass, after your own configuration.

The class carries @AutoConfiguration (a @Configuration without CGLIB proxies, with before/after to order it relative to others).

Step 3 of 9

Conditional beans

An auto-configuration is a @Configuration whose parts carry conditions:

  • On the class: @ConditionalOnProperty(prefix = "box.scoreboard", name = "enabled", havingValue = "true", matchIfMissing = true). On unless you set box.scoreboard.enabled=false.
  • On the @Bean: @ConditionalOnMissingBean. Only if there's no Scoreboard yet.

The most asked family of conditions: @ConditionalOnClass / @ConditionalOnMissingClass, @ConditionalOnBean / @ConditionalOnMissingBean, @ConditionalOnProperty, @ConditionalOnWebApplication / @ConditionalOnNotWebApplication and @ConditionalOnResource. All are built on Spring Framework's @Conditional.

Step 4 of 9

Back-off: your bean wins

If the application declares its own Scoreboard (here, tvScoreboard), @ConditionalOnMissingBean sees it and the auto-configuration doesn't create its own. A single bean remains: yours.

It works because auto-configurations are processed after the user's configuration.

Step 5 of 9

Reacting to the classpath

Optional parts switch on according to the classpath and the application type:

  • ScoreboardWebConfiguration needs @ConditionalOnWebApplication and @ConditionalOnClass(name = "…DispatcherServlet"): the controller only appears in web apps with Spring MVC.
  • JdbcScoreboardConfiguration asks for JdbcTemplate, which is not in this module: it isn't created.

All of Boot works this way: adding spring-boot-starter-data-jpa puts Hibernate on the classpath and its auto-configurations switch on; removing it switches them off.

Step 6 of 9

Testing auto-configurations: ApplicationContextRunner

To test each branch without starting the whole application, ApplicationContextRunner creates small, fast contexts:

  • .withConfiguration(AutoConfigurations.of(ScoreboardAutoConfiguration.class)): the auto-configuration under test.
  • .withPropertyValues(...), .withUserConfiguration(...): properties and user beans.
  • .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)): pretends a class is missing.
  • WebApplicationContextRunner for a web context.

assertThat(ctx).hasSingleBean(...) / doesNotHaveBean(...) check the outcome.

Step 7 of 9

The condition evaluation report

Why don't I have a DataSource? Why was this bean created? Start with debug=true (or --debug) and Boot prints the condition evaluation report:

  • Positive matches: auto-configurations applied and why.
  • Negative matches: those discarded and which condition failed.
  • Exclusions and Unconditional classes.

The test reads that same report (ConditionEvaluationReport) and checks that ScoreboardAutoConfiguration#scoreboard was applied and that there's no DataSource (no JDBC on the classpath). With Actuator, the /actuator/conditions endpoint gives the same as JSON.

Step 8 of 9

Excluding an auto-configuration

If you don't want an auto-configuration:

  • @SpringBootApplication(exclude = ScoreboardAutoConfiguration.class), or excludeName = "…" if the class may not be on the classpath.
  • The spring.autoconfigure.exclude=… property, which lets you do it per environment without touching code (what the test uses).

Step 9 of 9

Recap

  • @EnableAutoConfiguration loads the classes from AutoConfiguration.imports, after your configuration.
  • Conditions: OnClass, OnMissingBean, OnProperty, OnWebApplication…
  • Back-off: your bean wins; it's the normal way to customize Boot.
  • debug=true → condition report; exclude / spring.autoconfigure.exclude to remove them.
  • ApplicationContextRunner + FilteredClassLoader to test them.
  • A custom starter = an -autoconfigure module + a -starter module with the dependencies.

Cheatsheet →

Code

CopyPastedScoreboardConfig.java

/** Before: every box app copied this class, and nobody could switch the scoreboard off or replace it. */
public class CopyPastedScoreboardConfig {
    @Bean
    Scoreboard scoreboard() {
        return new ConsoleScoreboard("CrossFit Norte");  // hard-coded, always created
    }

    @Bean
    ScoreboardController scoreboardController(Scoreboard scoreboard) {
        return new ScoreboardController(scoreboard);     // even in apps without a web layer
    }
}

ScoreboardAutoConfiguration.java

@AutoConfiguration                                       // listed in META-INF/spring/…AutoConfiguration.imports
@ConditionalOnProperty(prefix = "box.scoreboard", name = "enabled",
                       havingValue = "true", matchIfMissing = true)  // on unless box.scoreboard.enabled=false
public class ScoreboardAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                            // back off if the app defines its own Scoreboard
    public Scoreboard scoreboard(@Value("${box.scoreboard.title:Scoreboard}") String title) {
        return new ConsoleScoreboard(title);
    }
    // …
}

ScoreboardAutoConfiguration.java

@AutoConfiguration                                       // listed in META-INF/spring/…AutoConfiguration.imports
@ConditionalOnProperty(prefix = "box.scoreboard", name = "enabled",
                       havingValue = "true", matchIfMissing = true)  // on unless box.scoreboard.enabled=false
public class ScoreboardAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                            // back off if the app defines its own Scoreboard
    public Scoreboard scoreboard(@Value("${box.scoreboard.title:Scoreboard}") String title) {
        return new ConsoleScoreboard(title);
    }
    // …
}

ScoreboardAutoConfigurationTest.java

@Configuration
static class MyOwnScoreboard {
    @Bean
    Scoreboard tvScoreboard() {                      // the app's own bean…
        return new Scoreboard() {
            public String title() { return "TV"; }
            public void post(String a, String r) { }
            public List<String> lines() { return List.of(); }
        };
    }
}

@Test
void theAutoConfigurationBacksOffWhenTheAppHasItsOwnBean() {
    runner.withUserConfiguration(MyOwnScoreboard.class)
        .run(ctx -> {
            assertThat(ctx).hasSingleBean(Scoreboard.class);           // …so only ONE Scoreboard
            assertThat(ctx.getBean(Scoreboard.class).title()).isEqualTo("TV");
        });
}

@Test
void aPropertySwitchesItOff() {
    runner.withPropertyValues("box.scoreboard.enabled=false")
        .run(ctx -> assertThat(ctx).doesNotHaveBean(Scoreboard.class));
}

ScoreboardAutoConfiguration.java

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication                         // only in a web application…
@ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet") // …with Spring MVC around
static class ScoreboardWebConfiguration {
    @Bean
    ScoreboardController scoreboardController(Scoreboard scoreboard) {
        return new ScoreboardController(scoreboard);
    }
}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate") // not on this classpath
static class JdbcScoreboardConfiguration {
    @Bean
    String jdbcScoreboardTable() {
        return "scoreboard";
    }
}

ScoreboardAutoConfigurationTest.java

private final ApplicationContextRunner runner = new ApplicationContextRunner()   // a tiny context per test
    .withConfiguration(AutoConfigurations.of(ScoreboardAutoConfiguration.class));

@Test
void byDefaultTheConsoleScoreboardIsCreated() {
    runner.withPropertyValues("box.scoreboard.title=Norte")
        .run(ctx -> {
            assertThat(ctx).hasSingleBean(Scoreboard.class);
            assertThat(ctx.getBean(Scoreboard.class)).isInstanceOf(ConsoleScoreboard.class);
            assertThat(ctx.getBean(Scoreboard.class).title()).isEqualTo("Norte");
        });
}

BootIntegrationTest.java

@Test
void theConditionReportExplainsEveryDecision() {
    ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory());

    assertThat(report.getConditionAndOutcomesBySource())        // what debug=true prints at startup
        .containsKey(ScoreboardAutoConfiguration.class.getName())
        .hasEntrySatisfying(ScoreboardAutoConfiguration.class.getName() + "#scoreboard",
            outcomes -> assertThat(outcomes.isFullMatch()).isTrue());
    assertThat(context.containsBean("dataSource")).isFalse();    // no JDBC on the classpath: no DataSource
}

BootIntegrationTest.java

@Test
void anAutoConfigurationCanBeExcluded() {
    try (var ctx = new SpringApplicationBuilder(BoxApplication.class)
            .web(WebApplicationType.NONE)
            .properties("spring.autoconfigure.exclude=" + ScoreboardAutoConfiguration.class.getName())
            .run()) {
        assertThat(ctx.getBeansOfType(Scoreboard.class)).isEmpty();
    }
}

ScoreboardAutoConfiguration.java

@AutoConfiguration                                       // listed in META-INF/spring/…AutoConfiguration.imports
@ConditionalOnProperty(prefix = "box.scoreboard", name = "enabled",
                       havingValue = "true", matchIfMissing = true)  // on unless box.scoreboard.enabled=false
public class ScoreboardAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                            // back off if the app defines its own Scoreboard
    public Scoreboard scoreboard(@Value("${box.scoreboard.title:Scoreboard}") String title) {
        return new ConsoleScoreboard(title);
    }
    // …
}

Quiz

1. Where does Spring Boot 3/4 look for candidate auto-configuration classes?

2. An auto-configuration declares @Bean @ConditionalOnMissingBean Scoreboard scoreboard(). Your application defines its own Scoreboard bean. What happens?

3. What does @ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate") do?

4. How do you see why an auto-configuration was applied or not?

5. How do you disable one specific auto-configuration?

6. What is ApplicationContextRunner for?

Cheatsheet → · Mock exam →

Run it