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:
- The starter puts the libraries on the classpath.
- Auto-configuration checks its conditions and creates beans.
- 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?"