Auto-configuration and starters
Mid-level Always asked 6 min
On this page
The question
What does @SpringBootApplication do? 30-second answer
It combines three annotations. @SpringBootConfiguration marks the class as a configuration source. @ComponentScan finds your beans in this package and below. @EnableAutoConfiguration loads candidate configurations from the classpath, and each registers beans only if its conditions pass. SpringApplication.run then starts the context and, for a web application, the embedded server.
Understand it
Conditions evaluated at startup
Step by step@SpringBootApplication combines three annotations: @SpringBootConfiguration, @ComponentScan and @EnableAutoConfiguration. Each one starts part of what follows.
View as text
A heading line above a table of three candidates: web server, RabbitMQ and DataSource. Columns show whether the class is on the classpath, whether you have no bean of your own, and the result.
@SpringBootApplication combines three annotations: @SpringBootConfiguration, @ComponentScan and @EnableAutoConfiguration. Each one starts part of what follows.
The component scan runs first. Your own beans are registered before any auto-configuration is considered, so conditions can see them.
Boot reads the AutoConfiguration.imports files from its jars: several hundred candidate classes. Each is only a candidate until its conditions pass.
@ConditionalOnClass asks whether the library is on the classpath. Tomcat and the DataSource types are. RabbitMQ is not, so that candidate is skipped. The RabbitMQ row is marked as skipped.
@ConditionalOnMissingBean asks whether you already defined one. You declared a DataSource, so Boot backs off and uses yours. The DataSource row reads yours.
Only the web server is auto-configured here. The result is a normal context, and running with --debug prints this report of matches and misses. The web server row reads registered.
A heading line above a table of three candidates: web server, RabbitMQ and DataSource. Columns show whether the class is on the classpath, whether you have no bean of your own, and the result.
@SpringBootApplication combines three annotations: @SpringBootConfiguration, @ComponentScan and @EnableAutoConfiguration. Each one starts part of what follows.
The component scan runs first. Your own beans are registered before any auto-configuration is considered, so conditions can see them.
Boot reads the AutoConfiguration.imports files from its jars: several hundred candidate classes. Each is only a candidate until its conditions pass.
@ConditionalOnClass asks whether the library is on the classpath. Tomcat and the DataSource types are. RabbitMQ is not, so that candidate is skipped. The RabbitMQ row is marked as skipped.
@ConditionalOnMissingBean asks whether you already defined one. You declared a DataSource, so Boot backs off and uses yours. The DataSource row reads yours.
Only the web server is auto-configured here. The result is a normal context, and running with --debug prints this report of matches and misses. The web server row reads registered.
Takeaway: Auto-configuration is a list of candidates, each behind conditions. Starters put libraries on the classpath, and your own beans always win.
Add a dependency and watch beans appear
ExploreThe web starter adds Tomcat, DispatcherServlet and a JSON mapper. With no JPA starter, the database setting changes nothing.
View as text
Two groups of bean boxes. The web group holds DispatcherServlet, Tomcat and a JSON mapper. The data group holds DataSource, EntityManagerFactory, JdbcTemplate and a TransactionManager. Each box says auto, yours or absent, and a mark says whether the context starts.
Only the base starter: no web server and no database beans, whatever the database setting says. Boot configures nothing you did not bring in.
The web starter adds Tomcat, DispatcherServlet and a JSON mapper. With no JPA starter, the database setting changes nothing.
Both starters add their beans side by side, and the embedded database gives JPA something to connect to.
Both starters are in, and you declared a DataSource, so Boot backs off that one bean and builds JPA on yours.
The JPA starter wants a DataSource, but there is no driver and no URL. Startup fails: Failed to determine a suitable driver class.
Two groups of bean boxes. The web group holds DispatcherServlet, Tomcat and a JSON mapper. The data group holds DataSource, EntityManagerFactory, JdbcTemplate and a TransactionManager. Each box says auto, yours or absent, and a mark says whether the context starts.
Only the base starter: no web server and no database beans, whatever the database setting says. Boot configures nothing you did not bring in.
The web starter adds Tomcat, DispatcherServlet and a JSON mapper. With no JPA starter, the database setting changes nothing.
Both starters add their beans side by side, and the embedded database gives JPA something to connect to.
Both starters are in, and you declared a DataSource, so Boot backs off that one bean and builds JPA on yours.
The JPA starter wants a DataSource, but there is no driver and no URL. Startup fails: Failed to determine a suitable driver class.
Takeaway: A starter brings libraries, the libraries satisfy conditions, and the conditions register beans. Remove the dependency and the beans go. Declare your own and Boot backs off.
In code
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
// Boot's DataSource is @ConditionalOnMissingBean, so this one is used
@Bean
DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
}@AutoConfiguration
@ConditionalOnClass(AuditClient.class)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "audit.enabled", matchIfMissing = true)
AuditClient auditClient(AuditProperties properties) {
return new AuditClient(properties.url());
}
}
// Listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsjava -jar shop.jar --debug # prints the CONDITIONS EVALUATION REPORT at startup
curl localhost:8080/actuator/conditions # the same report from a running app, once the endpoint is exposedSolve it
Production quietly uses an in-memory H2 database
After a deploy, orders disappear on every restart. The startup log shows a jdbc:h2:mem: URL, yet production should use
PostgreSQL. Find which auto-configuration made that choice and why, then make the mistake impossible.
- Ask Boot. Start with
--debug. The report showsDataSourceAutoConfigurationmatched and created an embedded database. - Know the rule. With no
spring.datasource.urlset and an embedded driver such as H2 on the classpath, Boot creates an in-memory database instead of failing. - Find the missing URL. The
prodprofile was not active, soapplication-prod.ymlwith the URL was never loaded. - Find why H2 is there. It was declared as a runtime dependency for tests, so it shipped in the jar.
- Fix and fail fast. Activate
prodin the deployment and scope H2 to tests. Without H2 a missing URL now stops startup with “Failed to configure a DataSource”.
spring:
datasource:
url: jdbc:postgresql://db:5432/shop
username: shop
password: ${DB_PASSWORD}SPRING_PROFILES_ACTIVE=prod java -jar shop.jar --debug | grep -A3 "DataSourceAutoConfiguration"How to answer
- Put the main class in the root package, because the scan starts there.
- Your beans are registered first, so conditions can see them.
- Starters supply the libraries; auto-configuration supplies the beans.
- It is a shorthand, and each of the three can be used on its own.
Common mistakes
- Calling auto-configuration "magic", with no mention of conditions.
- Saying
@SpringBootApplicationis what starts the server, rather thanSpringApplication.run.
Follow-up questions
How does auto-configuration decide what to configure?
Boot reads the candidate classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in each jar. Each is a @Configuration behind conditions: @ConditionalOnClass checks the classpath, @ConditionalOnMissingBean checks your beans, and @ConditionalOnProperty checks settings. Only classes that pass are applied. Spring Boot 2.7 introduced this file, replacing the spring.factories entry.
- There are several hundred candidates, and most are skipped on any one application.
@ConditionalOnWebApplicationand@ConditionalOnBeanare other common conditions.- Conditions on missing beans are why ordering matters, and why your beans go first.
See it in the infographic: Conditions evaluated at startup See it in the infographic: Add a dependency and watch beans appear
What is a Spring Boot starter?
A dependency with almost no code that brings a tested set of libraries for one purpose. spring-boot-starter-web, called spring-boot-starter-webmvc from Boot 4, brings Spring MVC (Model-View-Controller), Tomcat and JSON support. Versions come from Boot's dependency management, so you do not pick them one by one. The libraries then satisfy the conditions of auto-configuration, which registers the beans.
- A starter brings dependencies; auto-configuration creates beans.
- Swap Tomcat by excluding it and adding another server's starter.
- A third-party starter is named
acme-spring-boot-starter, notspring-boot-starter-acme.
See it in the infographic: Add a dependency and watch beans appear
You define your own DataSource bean. What happens to Boot's auto-configured one?
Boot backs off. Its DataSource sits behind @ConditionalOnMissingBean, so your bean satisfies the type and Boot's is never created. Everything built on it, such as the EntityManagerFactory and JdbcTemplate, is still auto-configured and uses yours, so the context holds one DataSource, named after your method.
- Replace the smallest piece that does what you need.
- Properties such as
spring.datasource.urlare often enough. - With your own bean, the
spring.datasource.*properties no longer configure it for you.
See it in the infographic: Conditions evaluated at startup See it in the infographic: Add a dependency and watch beans appear
You add the JPA (Jakarta Persistence API) starter and the application stops starting, with a driver or URL error. Why?
The starter put JPA on the classpath, so its auto-configuration now wants a DataSource. With no driver and no spring.datasource.url, Boot cannot build one, and startup fails with "Failed to determine a suitable driver class". Add an embedded database, set the URL and driver for a real one, or exclude the configuration if you do not need a database yet.
- A dependency alone can change what starts.
- An embedded database such as H2 on the classpath needs no URL.
- Boot's failure analyzer prints a description and a suggested action.
See it in the infographic: Add a dependency and watch beans appear
How would you write your own auto-configuration?
Write a class with @AutoConfiguration, and guard it with @ConditionalOnClass. Mark each @Bean with @ConditionalOnMissingBean, so applications can override it. Bind settings with @ConfigurationProperties. List the class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Publish it in a starter, and test with ApplicationContextRunner, trying each condition.
- Do not put an auto-configuration in the application's scanned packages.
@AutoConfiguration(after = ...)orders it relative to others.ApplicationContextRunnerstarts a small context for each case, quickly.
@AutoConfiguration
@ConditionalOnClass(AuditClient.class)
public class AuditAutoConfiguration {
@Bean
@ConditionalOnMissingBean
AuditClient auditClient() {
return new AuditClient();
}
} How do you see why a bean was or was not auto-configured?
Start the application with --debug to print the conditions evaluation report: positive matches, negative matches and the reason for each. With Actuator, /actuator/conditions shows the same report if the endpoint is exposed. Reading it beats guessing.
How do you turn one auto-configuration off?
Use the exclude attribute of @SpringBootApplication, or the spring.autoconfigure.exclude property. Before doing that, check whether declaring your own bean or setting a property is enough, since most auto-configurations back off or can be switched off with a setting.
Why does a shared library use auto-configuration rather than a wider component scan?
A scan would force every application to know the library's package and take all of its beans. An auto-configuration is listed in the library's jar, so it is found alone, and its conditions let each application turn parts off or replace them. It also runs after the application's own beans, so @ConditionalOnMissingBean works.
Check yourself
Show answers
- It puts a set of libraries on the classpath.: Correct. A starter is only dependencies. Auto-configuration then sees those classes and registers beans.
- It registers beans directly.: Incorrect. Starters hold almost no code. Beans come from auto-configuration classes behind conditions.
- It generates configuration files in the project.: Incorrect. Nothing is generated. Everything is decided at startup from the classpath and your beans.
Show answers
- It skips its DataSource and builds JPA on yours.: Correct. @ConditionalOnMissingBean fails for that one bean. The rest of JPA is still configured, using yours.
- It creates both, and fails with two candidates.: Incorrect. Boot's condition sees your bean first, so its own is never created.
- It turns off all JPA auto-configuration.: Incorrect. Only that single bean backs off. The EntityManagerFactory is still created.
Show answers
- @ConditionalOnClass: Correct. It checks the classpath, which is how adding a starter switches a feature on.
- @ConditionalOnMissingBean: Incorrect. That one checks your beans, which is how you override Boot's choice.
- @ConditionalOnProperty: Incorrect. That one checks a setting, not the classpath.