How it works
The explanation, with examples you can run.
Starters and auto-configurations are different things
A starter is a Maven or Gradle dependency with no code of its own; it pulls in a coherent set of libraries. An auto-configuration is a class marked @AutoConfiguration, shipped mostly in spring-boot-autoconfigure, and listed in a file called META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. @SpringBootApplication includes @EnableAutoConfiguration, which reads those files from every jar and evaluates each class after your own configuration has been registered.
Conditions
A simplified version of what Boot does for a connection pool looks like this:
@AutoConfiguration@ConditionalOnClass(DataSource.class) // the JDBC API is present@EnableConfigurationProperties(DataSourceProperties.class)public class MyDataSourceAutoConfiguration { @Bean @ConditionalOnMissingBean(DataSource.class) // you haven't made one @ConditionalOnProperty(prefix = "spring.datasource", name = "url") DataSource dataSource(DataSourceProperties props) { return props.initializeDataSourceBuilder().build(); }}The conditions you will see most:
@ConditionalOnClass/@ConditionalOnMissingClass: is a library on the classpath?@ConditionalOnBean/@ConditionalOnMissingBean: has someone already defined this?@ConditionalOnProperty: is a property set (by default, present and notfalse)?@ConditionalOnWebApplication: is this a servlet or reactive web app?
Because the auto-configuration runs last and backs away when your bean exists, the way to customise Boot is usually to declare the bean yourself, or, better still, to set a property that Boot's own bean reads.
Seeing the decisions
Start the application with --debug (or debug=true in application.properties) and Boot prints a conditions evaluation report: every auto-configuration, whether it matched, and which condition decided. With Actuator, /actuator/conditions shows the same at runtime, if you expose it.
DataSourceAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.sql.DataSource', ...MongoAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient'To switch one off entirely:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)public class App { }The same mechanism is open to you: a company "starter" for logging or tracing is an auto-configuration class, an imports file and a few conditions, so teams get sensible defaults they can still override.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.