Skip to the workspace
Pebellslearn by building
Auto-configuration  ›  Lesson

How Auto-configuration Works

Autoconfiguration 12 minAuto-configuration classes create beans only when the needed libraries are on the classpath and you have not defined the bean yourself.

spring boot / How Auto-configuration Works

Explore each scene at your own pace.

01 · The rule

The rule

How Auto-configuration Works

You added spring-boot-starter-data-jpa and the PostgreSQL driver to library-service, set three properties, and suddenly there is a connection pool, a Hibernate setup, a transaction manager and working repositories. You never wrote a @Bean for any of them. That is auto-configuration, and it is not magic: it is ordinary configuration classes that someone else wrote, switched on by conditions.

The rule

Boot looks at your classpath and your beans, then fills in only what is missing.

@SpringBootApplication includes @EnableAutoConfiguration. At startup, that annotation loads a list of auto-configuration classes shipped inside the spring-boot-autoconfigure jar and inside third-party starters. In Boot 3, each jar lists its classes in a file named META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.

Each auto-configuration class is a normal configuration class full of @Bean methods, guarded by conditions. A simplified picture of how Boot sets up a data source:

@AutoConfiguration
@ConditionalOnClass(DataSource.class)            // only if JDBC is on the classpath
public class SimpleDataSourceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(DataSource.class)  // only if you did not define one
    public DataSource dataSource(DataSourceProperties props) {
        return props.initializeDataSourceBuilder().build();
    }
}

The props come from your spring.datasource.url, username and password properties. So the three pieces fit together like this:

  1. The starter puts the libraries on the classpath.
  2. Auto-configuration checks its conditions and creates beans.
  3. Properties tune those beans without any code.

Auto-configuration runs after your own configuration has been read. That ordering is what lets it ask, "Has the developer already defined this bean?"

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.