Card 03/ 06

ExampleDifficulty: Intermediate1 min

Auto-Configuration Example: A DataSource You Never Defined

A database library on the classpath and no configuration, and the context still hands out a connection pool.

Auto-configuration is the part of Boot that creates beans for you when certain conditions hold. The application below never declares a DataSource (the object that hands out database connections), yet asking the context for one returns a real, connected one.

H2, a small database that can run in memory, is on the classpath, and nothing else is configured:

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 checks that the classes it needs are on the classpath, and @ConditionalOnMissingBean checks that you have not already defined a DataSource yourself. Both conditions held, so it created a HikariDataSource, a connection pool (a set of open connections that are reused), pointed at an in-memory H2 database.

So the libraries you add decide which beans appear: adding a database driver is enough to get a DataSource, without a line of configuration.