Card 04/ 06

GotchaDifficulty: Intermediate1 min

Your Bean Wins

Define a DataSource bean yourself, in the same application that would otherwise have had one auto-configured, and nothing complains about a conflict — your version is the one that gets used, with no warning that the other one was even considered.

java
@SpringBootApplication
public class CustomDataSourceWins {

    @Bean
    DataSource dataSource() {
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:mem:custom");
        return ds;
    }

    public static void main(String[] args) {
        var context = SpringApplication.run(CustomDataSourceWins.class, args);
        DataSource dataSource = context.getBean(DataSource.class);
        System.out.println("DataSource bean class: " + dataSource.getClass().getName());
    }
}
text
DataSource bean class: org.h2.jdbcx.JdbcDataSource
run in a container — not HikariDataSource this time

@ConditionalOnMissingBean is doing exactly what its name says: it checked whether a DataSource bean already existed before creating its own, found yours, and backed off entirely. This is the rule behind every auto-configured bean, not just this one — a bean you define always takes priority over the one Boot would otherwise have created for the same purpose.