Card 03/ 06
All 6 cards
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.
@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());
}
}DataSource bean class: HikariDataSourceDataSourceAutoConfiguration 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.