Card 04/ 06
Your Own Bean Replaces the Auto-Configured One
Define a DataSource yourself and Boot quietly backs off, with no warning that it considered one.
When you define a bean yourself, Boot's auto-configuration (Boot creating beans for you based on what is on the classpath) does not create its own bean of the same type. Yours is used, and nothing reports that Boot's was skipped. That is the intended rule, and it surprises people who expect a conflict or a warning.
Define a DataSource bean in an application that would otherwise get an auto-configured one, and there is no error about two data sources:
@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());
}
}DataSource bean class: org.h2.jdbcx.JdbcDataSourceBoot's DataSource auto-configuration carries @ConditionalOnMissingBean, a condition that only creates the bean when none of that type exists yet, and it did exactly what its name says: it checked whether a DataSource bean already existed, found yours, and backed off entirely. The same rule guards almost every auto-configured bean, so a bean you define of the same type takes priority.
The surprise is losing what Boot's version gave you. Boot's DataSource was a connection pool configured from the spring.datasource.* properties; yours is exactly what you wrote, here a plain H2 data source (H2 is a small database that runs inside the application) with no pool, and those properties no longer apply.
Define your own bean only when you need something the properties cannot express, and otherwise configure Boot's bean through spring.datasource.*. To see which auto-configurations ran and which backed off, start the application with --debug, which prints the conditions report.
← → move through sections and cards