Card 03/ 06

ExampleDifficulty: Intermediate1 min

A DataSource You Never Defined

This application never declares a DataSource bean. H2 is on its classpath and nothing else is configured. Asking the context for a DataSource anyway gets a real, connected one.

java
@SpringBootApplication
public class AutoConfigDemo {
    public static void main(String[] args) {
        var context = SpringApplication.run(AutoConfigDemo.class, args);
        DataSource dataSource = context.getBean(DataSource.class);
        System.out.println("DataSource bean class: " + dataSource.getClass().getSimpleName());
    }
}
text
DataSource bean class: HikariDataSource
run in a container, Spring Boot 3.3.4

DataSourceAutoConfiguration is a class Spring Boot ships, guarded by conditional annotations — @ConditionalOnClass, checking that a DataSource type and an embedded database driver are both on the classpath, and @ConditionalOnMissingBean, checking that you haven't already defined one yourself. Both conditions passed, so it created a pooled HikariDataSource pointed at an in-memory H2 database, entirely from what it found.