Sub topic 7
Overriding, backing off, and excluding auto-configuration
This chapter assumes you know how @Configuration and @Bean work and what a bean type is. You should also have seen the earlier chapters on @SpringBootApplication, conditional annotations, and @ConfigurationProperties. Here you will learn the three ways to change what Boot configures for you, and how to choose between them.
Three levers, in order of preference
Auto-configuration is a set of defaults. When a default does not fit, you have three ways to change it. Use the lightest one that works.
| Lever | What you do | When to use it |
|---|---|---|
| Tune | Set a property such as `server.port` or `greeting.message` | The default behavior is right, but a value is wrong |
| Replace (back off) | Define your own bean of the same type | You need different behavior, but you still want the rest of the feature |
| Exclude | Tell Boot to skip an auto-configuration class entirely | You want none of that feature, or it fails in your environment |
Tuning was covered in the previous chapter. This chapter focuses on replacing and excluding.
How backing off works
Most auto-configured beans are guarded by @ConditionalOnMissingBean. The condition asks one question: does the application context already contain a bean of this type? If the answer is yes, Boot skips its own definition. This is called backing off.
Backing off only works because of ordering. Boot processes auto-configuration classes after your own configuration classes. By the time a @ConditionalOnMissingBean condition is evaluated, your bean definitions are already registered.
Recall the auto-configuration from the earlier chapter:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}An application can replace the bean by declaring its own GreetingService:
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public GreetingService greetingService() {
return new GreetingService("Welcome");
}
}At startup, Boot evaluates @ConditionalOnMissingBean on greetingService, finds the bean from AppConfig, and does not register its own. The application gets Welcome, Ann! instead of Hello, Ann!. The greeting.message property no longer has any effect here, because the auto-configured bean that read it was skipped. Your replacement bean is responsible for its own settings.
What counts as "missing"
@ConditionalOnMissingBean on a @Bean method looks at the method's return type by default. Three consequences follow.
- Your bean must be assignable to the type the auto-configuration declares. If the auto-configuration returns
GreetingServiceand your bean is declared asObject, the condition does not see a match. - Declare the most useful type as the return type of your
@Beanmethod. A method returningGreetingServiceImplstill matches a check forGreetingService, because Boot also considers the actual type of an already-created bean. Declaring the interface or base class is the safer habit. - The condition can also be written with
name,value, orignoredattributes, for example@ConditionalOnMissingBean(name = "greetingService"). Auto-configurations written this way match by bean name instead of type.
Replacing one part, keeping the rest
Many features register several beans. Because each bean has its own @ConditionalOnMissingBean, you can replace one and keep the others. For example, if you define your own ObjectMapper, Boot's JacksonAutoConfiguration skips its default ObjectMapper. Its other Jackson beans stay in place. This is why replacing a bean is usually better than excluding the whole class.
Excluding an auto-configuration
Excluding removes a class from the candidate list before any condition runs. There are three ways to do it.
Using the annotation attribute, which is checked by the compiler:
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);
}
}Using excludeName, which takes the fully qualified class name as a string. Use it when the class is not on your compile classpath:
@SpringBootApplication(excludeName = "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration")Using a property, which needs no code change and can differ per environment:
# application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationThe property accepts a comma-separated list. Exclusions from the annotation and the property are combined.
Exclusion does not remove the library
Excluding DataSourceAutoConfiguration stops Boot from creating a DataSource. The JDBC driver and connection pool stay on the classpath. Other auto-configurations that depend on a DataSource, such as JPA, will then fail or back off, depending on their own conditions. Exclusion changes the bean graph, not your dependencies. If you never need the feature, remove the starter from the build instead.
Switching features off with properties
Many auto-configurations carry @ConditionalOnProperty, which gives you a documented off-switch without any exclusion. You can add the same switch to your own auto-configuration:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}With matchIfMissing = true, the feature is on unless a user sets greeting.enabled=false. Without matchIfMissing, a missing property counts as a mismatch, so the feature would be off by default. Pick the default deliberately. Library authors usually choose on-by-default for core features and off-by-default for features that cost resources or open network ports.
Gotchas and common errors
Your bean is ignored, or the default wins
Boot's default is created anyway if your bean is not visible when the condition runs. Typical causes:
- Your configuration class is outside the component-scan base package, so it is never loaded. The scan starts at the package of the
@SpringBootApplicationclass. - You registered the bean from another auto-configuration with no ordering relationship. Ordering is covered in a later chapter.
- Your bean's declared type does not match the type being checked.
Two beans with the same name
Suppose you name your bean the same as the auto-configured one but declare a different return type. The type-based condition sees no match and Boot registers its default. Two definitions then share one name. Bean definition overriding is disabled by default in Boot, so startup fails with a BeanDefinitionOverrideException. Fix it by returning the expected type, or by choosing a different bean name. Enabling spring.main.allow-bean-definition-overriding=true hides the symptom and makes the winning bean depend on load order, so avoid it.
Whole features switched off by one annotation
Some annotations and base classes disable an entire auto-configuration. The best-known case is @EnableWebMvc. WebMvcAutoConfiguration is guarded by @ConditionalOnMissingBean(WebMvcConfigurationSupport.class), and @EnableWebMvc imports exactly that type. Adding the annotation therefore turns off Boot's Spring MVC defaults, including static resource handling and JSON converter setup. If you only want to add a view controller or an interceptor, implement WebMvcConfigurer and leave @EnableWebMvc off.
Unexpected back-off from an unrelated bean
A conditional on a broad type can back off for a reason you did not intend. If you define any DataSource bean, even a test double, Boot's DataSourceAutoConfiguration skips its own. This is usually what you want. It becomes a surprise when you define the bean in a shared configuration class that is picked up in every profile.
Using `@ConditionalOnBean` in your own code
@ConditionalOnBean is the opposite check and is only reliable in auto-configurations, because it depends on all other bean definitions already being registered. In an ordinary @Configuration class the result depends on class processing order. Use it in auto-configurations and order them explicitly.
Checking what happened
When a bean is not what you expected, ask Boot to explain its decisions:
java -jar app.jar --debugThe conditions report lists each auto-configuration under positive matches, negative matches, exclusions, and unconditional classes. The next chapter covers how to read it. For back-off problems, look for the negative-match entry that says @ConditionalOnMissingBean ... found beans of type .... It names the bean that caused Boot to step aside.
Choosing the lever
- Start with a property. If a documented property exists, it is the safest change.
- If behavior must change, define your own bean of the type the auto-configuration provides. Only that bean is replaced.
- Exclude the whole class only when no part of the feature is wanted, or when a part fails in your environment, for example when a data source cannot connect at startup in a test slice.
- If you also want the library off the classpath, remove the starter.
Exercise
An application sets spring.autoconfigure.exclude=com.example.app.MyOwnConfig, where MyOwnConfig is an ordinary @Configuration class in the application. What happens at startup, and what should you use instead?
Show answer
Startup fails with an IllegalStateException, because exclusion works only for classes registered as auto-configurations, and MyOwnConfig is not one. To disable it, guard it with a condition such as @ConditionalOnProperty and set that property, or move it out of the component-scan packages.
Exercise
Boot's auto-configuration defines GreetingService with @ConditionalOnMissingBean. You declare your own @Bean GreetingService greetingService() in a class under the application's base package, and greeting.message=Hi is set in application.properties. Which message does greet("Ann") use, and why?
Show answer
It uses the message your own bean was constructed with, not Hi. Boot's default bean is skipped because a GreetingService already exists, and the default bean was the only one that read greeting.message. Your bean must read the property itself, for example by injecting GreetingProperties.