Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 66 ยท Auto-Configuration and Configuration

How Auto-Configuration Works

See how Spring Boot auto-configuration finds, orders and conditionally applies configuration classes, backs off for your beans, and how to read the debug report.

You add spring-boot-starter-web and an embedded Tomcat, a DispatcherServlet and a JSON converter simply appear. You add a database driver and a DataSource is created. Nobody wrote that wiring in your project, and it feels like magic. It is not magic: it is ordinary @Configuration classes and the conditions from the previous lesson, loaded from a list, and applied after your own configuration.

This lesson opens that machinery. You will see where the list lives, how conditions pick which classes apply, why your own beans always win, how to read the debug report that explains every decision, and how to exclude an auto-configuration you do not want. The real Spring files and annotations are read-only. The two TryIts are plain-Java stand-ins that rebuild the engine in miniature, and each states what is real and what is imitation.

Auto-configuration in four steps

A list Boot reads the names of all candidate classes.
Conditions Each class checks the classpath, properties and beans.
Beans Classes that pass register their beans.
Back off Anything you defined yourself wins.

It is ordinary Spring configuration, applied last.

1 / 2

Switching it on

@SpringBootApplication is a shortcut for three annotations: @SpringBootConfiguration (this is a configuration class), @ComponentScan (find your components) and @EnableAutoConfiguration. The last one is the switch. It imports a special selector that reads the candidate list and hands the classes to the container.

Two timing facts make the whole design work:

  1. Your own configuration and scanned components are registered first.
  2. Auto-configuration classes are processed afterwards, in a deferred step.

Because of that order, @ConditionalOnMissingBean in an auto-configuration can reliably ask "did the user already define one?". The answer is already known.

The candidate list: AutoConfiguration.imports

Each Boot library that supplies auto-configuration includes a plain text file in its jar:

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

It contains one fully qualified class name per line (blank lines and # comments are allowed):

Text
# part of the spring-boot-autoconfigure jar
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

At startup Boot reads every such file from every jar on the classpath and merges the lines into one list. A starter that wants its own auto-configuration only needs to ship this file (Writing Your Own Starter). Older projects used the key org.springframework.boot.autoconfigure.EnableAutoConfiguration inside META-INF/spring.factories; Boot 2.7 deprecated that for auto-configuration and Boot 3 no longer reads it. If you maintain an old library, move its entries to the .imports file.

The listed classes are annotated with @AutoConfiguration, a specialised @Configuration. Besides marking the class, it can declare ordering with before and after so that, for example, the transaction manager configuration runs after the data source configuration.

A real auto-configuration, simplified

This is the shape of nearly every auto-configuration class. It is a simplified sketch, not the exact source:

Java
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnClass({ JdbcTemplate.class, DataSource.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {

    @Bean
    @Primary
    @ConditionalOnMissingBean(JdbcOperations.class)
    JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties properties) {
        JdbcTemplate template = new JdbcTemplate(dataSource);
        template.setFetchSize(properties.getTemplate().getFetchSize());
        return template;
    }
}

Read it top to bottom as a sentence: "after the data-source configuration, if the JDBC classes are on the classpath and there is exactly one DataSource bean, create a JdbcTemplate (configured from the JdbcProperties) unless the application already has one." Every Boot feature follows this pattern: class present, other prerequisites present, no user override, then create.

The conditions are the ones from Conditional Beans. Remember the rule that makes it safe: @ConditionalOnClass first, so nothing loads a missing library, then @ConditionalOnMissingBean on each @Bean, so you can always substitute your own.

Back off: you always win

If you define a JdbcTemplate bean yourself, the condition in the code above is false and Boot's version simply never exists. You override a default by declaring the bean; there is nothing to disable. Compare this with frameworks that need a "replace default" setting for every component. The same idea applies at every level: replace a single bean, tune it with properties (spring.jdbc.template.fetch-size), or turn off the whole auto-configuration.

A mini auto-configuration engine

The stand-in below follows the same steps with plain Java. A "classpath" is a set of names, user beans are registered first, and each auto-configuration class declares its required classes and the bean it provides. The engine applies conditions in listed order and prints a report in the style of Boot's.

Java A mini auto-configuration engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the output, objectMapper and dataSource come from auto-configuration, mongoClient is skipped because its class is missing, and mailSender stays yours because the engine backed off. What is real: the sequence "user beans first, then listed classes, each gated by conditions". What is the stand-in: real conditions are annotations evaluated by the container, many more kinds exist, and a bean's @Bean method is a recipe, not just a name.

Order between auto-configurations

Auto-configurations sometimes depend on each other. @AutoConfiguration(after = ..., before = ...) expresses that, and Boot sorts the list with those constraints (alphabetical order is the starting point, then the after and before rules are applied). The next TryIt reads an imports-style file, removes comments and blank lines, and orders entries with an after rule.

Java Reading an imports file and ordering by after

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Alphabetically the data source configuration would come last, but it moves to the front because the other two must come after it. The parsing rule (one name per line, # comments, blank lines ignored) matches the real file format. The dependency sort is a simple stand-in for Boot's own sorter.

Seeing every decision: the debug report

You do not have to guess why a bean exists. Start the application with the debug flag:

Terminal
java -jar app.jar --debug
# or, in application.properties:
# debug=true

Boot then prints a conditions evaluation report with these sections:

Text
============================
CONDITIONS EVALUATION REPORT
============================

Positive matches:
-----------------
   DataSourceAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', ...

Negative matches:
-----------------
   MongoAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient'

Exclusions:
-----------
    None

Unconditional classes:
----------------------
    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration

The positive matches are what was applied and why. Negative matches are what was skipped and which condition said no. Exclusions are classes you excluded on purpose, and unconditional classes always apply. When a bean you expected is missing, search the negative matches for its auto-configuration, and read the failing condition. In a running application, the Actuator conditions endpoint exposes the same report (Actuator: Health, Metrics and Info). The output of our stand-in above is shaped like it on purpose.

Excluding an auto-configuration

Sometimes you want a configuration not to apply at all, for instance to bring your own security setup or avoid a DataSource your application does not need. Two ways:

Java
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class ShopApplication { ... }
PROPERTIES
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Use excludeName (or the property) when the class is not on your compile classpath. An exclusion is a last resort: first try tuning with properties, or defining your own bean so the default backs off. Excluding a whole configuration also drops its other beans and its properties handling, which can surprise you later.

A very common beginner failure is adding a database starter without a database setting. Boot tries to build a DataSource, finds no URL, and refuses to start with "Failed to configure a DataSource". Either configure spring.datasource.url, or remove the dependency, or exclude DataSourceAutoConfiguration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does Boot find the list of auto-configuration classes in Boot 3 and later?

    Each jar can contribute an .imports file listing one class per line. Boot merges all of them. The old spring.factories entries for this purpose are no longer read in Boot 3.
  2. 2. Why can @ConditionalOnMissingBean in an auto-configuration reliably see your own beans?

    Auto-configuration is imported in a deferred step, so by the time its conditions are evaluated, your bean definitions are already registered.
  3. 3. In the conditions evaluation report, which section tells you why an auto-configuration was NOT applied?

    Negative matches list each skipped configuration with the condition that did not match. Exclusions lists only classes you removed explicitly.
  4. 4. You define your own ObjectMapper bean. What happens to Boot's default one?

    Defaults are guarded by @ConditionalOnMissingBean, so declaring your own bean is enough to replace them.

Summary

  • @EnableAutoConfiguration (part of @SpringBootApplication) loads candidate classes from AutoConfiguration.imports files in all jars on the classpath.
  • Each candidate is a normal @AutoConfiguration class gated by conditions: class present, properties set, other beans present or missing.
  • Auto-configuration runs after your own configuration, so @ConditionalOnMissingBean lets your beans replace any default.
  • --debug (or debug=true) prints the conditions evaluation report with positive matches, negative matches, exclusions and unconditional classes.
  • Exclude a configuration with exclude or spring.autoconfigure.exclude only as a last resort; prefer properties or your own bean.

Next: Writing Your Own Starter.