Sub topic 4
Auto-configuration: how Boot configures beans for you
This chapter assumes you know basic Java and annotations, and that you understand what a Spring bean is and how dependency injection wires beans together. It also assumes you have generated a project with a web starter. The chapter covers how Spring Boot decides which beans to create, how your own beans take priority, and how to see and change those decisions.
The problem auto-configuration solves
In plain Spring, a web application needs explicit setup. You declare a DispatcherServlet, a JSON converter, a view resolver, and a connection pool, and each one needs its own bean definition. Most projects write nearly the same definitions every time.
Auto-configuration moves that repeated setup into the framework. At startup, Boot looks at three things:
- The classpath. Which libraries are present?
- The existing beans. Which beans have you already defined?
- The properties. Which settings have you supplied?
Boot then registers the beans that fit. Add spring-boot-starter-web and you get Spring MVC, Jackson for JSON, and an embedded server, all wired together. Boot does not generate code or hide magic files. Auto-configuration is ordinary @Configuration classes that run only when their conditions hold.
Where it starts
The @SpringBootApplication annotation on your main class is a composite of three annotations:
@SpringBootConfiguration, a specialized@Configuration@ComponentScan, which finds your own components@EnableAutoConfiguration, which switches on the mechanism described here
@EnableAutoConfiguration imports a list of candidate configuration classes. In Spring Boot 3, the list comes from a file inside the spring-boot-autoconfigure JAR:
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsEach line is a fully qualified class name, such as org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration. Boot 2.6 and earlier listed these classes under the EnableAutoConfiguration key in META-INF/spring.factories. Boot 2.7 introduced the .imports file, and Boot 3 dropped the old key. Old blog posts and Stack Overflow answers often show the spring.factories form.
The list holds well over a hundred candidates. Most of them do nothing in a given application, because their conditions fail.
Conditions decide what applies
Every auto-configuration class is guarded by conditional annotations. If a condition fails, the class or bean is skipped. The most common conditions are these:
| Annotation | The configuration applies when... |
|---|---|
| `@ConditionalOnClass` | a named class is on the classpath |
| `@ConditionalOnMissingClass` | a named class is not on the classpath |
| `@ConditionalOnBean` | a bean of a given type already exists |
| `@ConditionalOnMissingBean` | no bean of a given type exists yet |
| `@ConditionalOnProperty` | a property is set, or has a given value |
| `@ConditionalOnWebApplication` | the application is a web application |
Two of these do most of the work. @ConditionalOnClass makes starters meaningful: adding a starter puts classes on the classpath, and those classes satisfy the conditions. @ConditionalOnMissingBean makes defaults replaceable, and the next section covers it.
The following diagram shows the decision for one bean.
Your beans win: backing off
Boot's defaults are written as @ConditionalOnMissingBean. A simplified version of the pattern looks like this:
@Bean
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}If you define your own ObjectMapper, the condition fails and Boot's version is never created. You never have to disable anything. You declare the bean you want:
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class JsonConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}Place this class in the same package as the main class, or in a sub-package, so component scanning finds it.
Replacing a bean also drops everything Boot did to it. Boot's ObjectMapper honors spring.jackson.* properties and registers modules found on the classpath, such as the Java time module. The bare new ObjectMapper() above does neither. If you only want to adjust Boot's mapper, prefer a property such as spring.jackson.default-property-inclusion=non_null. Alternatively, define a Jackson2ObjectMapperBuilderCustomizer bean, which modifies the builder and keeps the other defaults.
Auto-configuration is ordered after your code
Boot processes your configuration first and the auto-configuration classes afterward. This ordering is why @ConditionalOnMissingBean can see your beans. The same ordering explains a common mistake: using @ConditionalOnMissingBean or @ConditionalOnBean in your own ordinary @Configuration classes. Component-scanned classes have no guaranteed order relative to each other, so the condition can evaluate before the bean it checks for is registered, and the result may vary. Reserve these two conditions for auto-configuration classes. For application code, use @Profile or @ConditionalOnProperty, whose results do not depend on registration order.
Seeing what Boot decided
When a bean you expected is missing, or one you did not expect appears, ask Boot for its conditions report. Start the application with the --debug flag:
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debugYou can also set debug=true in application.properties. This is not the same as setting the log level of your own classes. It prints a report like this one, with wording that varies slightly between versions:
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches:
-----------------
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'
- @ConditionalOnWebApplication (required) found 'session' scope
Negative matches:
-----------------
DataSourceAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'The report has four sections:
- Positive matches: configurations that applied.
- Negative matches: configurations that were skipped, with the failed condition.
- Exclusions: classes you excluded by hand.
- Unconditional classes: classes that always apply.
Read the negative match for the class you care about. It names the exact condition that failed, which usually points to a missing dependency or an unset property.
Turning auto-configuration off
You can exclude a class in the annotation:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}You can also exclude it by property, which does not need the class on the compile classpath:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationExclusion is a blunt tool. Prefer a more specific property or your own bean where one exists, and keep exclude for cases where a library is on the classpath but you do not want it configured.
Common errors
- "Failed to configure a DataSource: 'url' attribute is not specified." You added a JDBC or JPA starter without a database driver or connection URL. Auto-configuration saw a
DataSourceneed and found nothing to satisfy it. Supplyspring.datasource.urland a driver, or remove the starter. - A default behaves differently after you add a bean. You replaced Boot's bean and lost its customization, as in the
ObjectMapperexample. Check the positive matches to confirm the default backed off. - Your configuration class is ignored. It sits outside the main class's package tree, so component scanning never finds it. Move it into the scanned packages.
ConditionalOnBeanworks on one machine and not another. This is the ordering problem above. Move the logic into auto-configuration or use a different condition.- Two beans of one type cause
NoUniqueBeanDefinitionException. You defined a second bean without removing the first. Boot's own defaults avoid this by backing off. Your own definitions need@Primaryor a qualifier. - A bean override fails at startup. Since Boot 2.1, defining two beans with the same name raises an error instead of silently overriding. Rename one bean.
Writing your own auto-configuration
Teams use the same mechanism to ship shared libraries. An auto-configuration class is a normal configuration class registered in the .imports file of your library's JAR:
package com.example.greeting;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService() {
return new GreetingService("Hello");
}
}GreetingService here is a simple class in the same library, and @AutoConfiguration is available from Boot 2.7. The library's META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file contains one line, com.example.greeting.GreetingAutoConfiguration. Applications that depend on the library get the default service, and any application can replace it by defining its own GreetingService bean.
Exercise
You add spring-boot-starter-web and define your own ObjectMapper bean. Boot's ObjectMapper is not created, and spring.jackson.default-property-inclusion no longer has any effect. Why, and what are two ways to keep the property working?
Show answer
Boot's ObjectMapper is declared with @ConditionalOnMissingBean, so it backs off when you define your own. Your bare new ObjectMapper() does not read spring.jackson.* properties. To keep the property working, either remove your bean and use the property or a Jackson2ObjectMapperBuilderCustomizer to adjust Boot's mapper, or build your bean from the injected Jackson2ObjectMapperBuilder so the properties still apply.
Exercise
An expected auto-configured bean is missing at runtime. Which flag shows why, and which section of its output do you read?
Show answer
Start the application with --debug (or set debug=true). Read the "Negative matches" section for the relevant auto-configuration class. It names the condition that failed, such as a missing class or an unset property.