Sub topic 5
Backing off when the user defines a bean
This chapter assumes you can write @Configuration classes with @Bean methods and that you know what @ConditionalOnClass does. You should also know that Spring Boot loads auto-configuration classes from the AutoConfiguration.imports file. The chapter covers the condition that makes auto-configuration overridable, @ConditionalOnMissingBean. It also covers its counterpart @ConditionalOnBean, which depends on processing order.
Why back-off exists
An auto-configuration supplies a sensible default. The default must never get in the way when the application wants something different. If a starter registered a GreetingService unconditionally and you defined your own, the context would hold two beans of the same type. Injection points would then fail with NoUniqueBeanDefinitionException, or the wrong bean would be used silently.
Spring Boot solves this with a convention. An auto-configuration registers its bean only if the application has not already registered one of that type. This is called backing off. The application wins, and the auto-configuration steps aside.
Here is the service used in this chapter's examples. The code assumes the GreetingService class below, together with the GreetingProperties class from the previous chapter.
package com.example.greeting;
public class GreetingService {
private final String message;
public GreetingService(String message) {
this.message = message;
}
public String greet(String name) {
return message + ", " + name + "!";
}
}@ConditionalOnMissingBean
@ConditionalOnMissingBean matches when the context contains no bean definition of the given type. This is the auto-configuration from the topic plan:
package com.example.greeting;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@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());
}
}The @ConditionalOnMissingBean annotation on the @Bean method has no attributes. In that case Spring Boot uses the method's return type, GreetingService, as the type to look for. Now an application can override the default by declaring its own bean:
package com.example.app;
import com.example.greeting.GreetingService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public GreetingService greetingService() {
return new GreetingService("Howdy");
}
}With AppConfig present, the auto-configured greetingService method is skipped. The bean named greetingService is the application's.
The return type is the matching type
The condition is evaluated while Spring is registering bean definitions, before any bean is created. Spring therefore cannot inspect the object your method returns. It reads the declared return type of the method.
Suppose you declare the return type as an interface:
@Bean
@ConditionalOnMissingBean
public Greeter greeter() {
return new GreetingService("Hello");
}The condition checks for a bean of type Greeter. A user bean declared as GreetingService also matches if GreetingService implements Greeter. A user bean declared with some unrelated return type does not match. Declare the return type that you want users to be able to replace.
Choosing what to match
You can state the match explicitly with attributes:
| Attribute | Matches on | Example |
|---|---|---|
| `value` or `type` | Bean type, as a class or class name | `@ConditionalOnMissingBean(GreetingService.class)` |
| `name` | Bean name | `@ConditionalOnMissingBean(name = "greetingService")` |
| `annotation` | Annotation present on the bean's class | `@ConditionalOnMissingBean(annotation = Primary.class)` |
| `search` | Which part of the context hierarchy to look in | `@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)` |
| `ignored` or `ignoredType` | Types to leave out of the check | `@ConditionalOnMissingBean(ignored = DefaultGreeting.class)` |
The search attribute takes a SearchStrategy. The default is ALL, which searches the current context and its parents. CURRENT looks only at the current context, and ANCESTORS looks only at parent contexts. This matters in applications with a parent and child context, such as some management-port setups. A bean in the parent context makes a child's ALL search match.
You can also put the annotation on a whole class instead of one method. The check then applies to the class as a unit. Use the method-level form for the usual case of one overridable bean. The class-level form fits a group of beans that should be replaced together.
Match by type, not by name
Matching by name is weaker than it looks. The bean greetingService in your AppConfig has the same name as the auto-configured one. Spring Boot disables bean definition overriding by default. If the auto-configuration did not back off, the application would fail at startup with a BeanDefinitionOverrideException. Type-based back-off avoids this because the auto-configured definition is never registered. Prefer a type check unless you have a reason to key on a name.
Order decides what a bean condition can see
Bean conditions do not look at beans. They look at bean definitions that have been registered so far. This is the key point of the chapter. The context is built in phases. Spring reads configuration classes one at a time, and each @Bean method turns into a bean definition as its class is processed. A bean condition evaluated early cannot see definitions that later classes will add.
Spring Boot arranges the order so that back-off works:
- Spring processes your own configuration classes first. These come from component scanning and from classes you register explicitly.
- Auto-configuration classes are processed after that. They are imported through a deferred import selector, which postpones them until all user configuration has been parsed.
So when @ConditionalOnMissingBean runs inside an auto-configuration, your AppConfig bean is already registered. The condition sees it and the default backs off.
@ConditionalOnBean and why it belongs in auto-configuration
@ConditionalOnBean is the opposite condition. It matches only if a bean of the given type is already defined. Use it when your configuration only makes sense alongside another component.
package com.example.audit;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnBean(DataSource.class)
public class AuditAutoConfiguration {
@Bean
public AuditLogger auditLogger(DataSource dataSource) {
return new AuditLogger(dataSource);
}
}Two things make this work.
- The class is an auto-configuration, so it is processed after user configuration. Your own
DataSourcebean, if you defined one, is already registered. after = DataSourceAutoConfiguration.classplaces it behind the auto-configuration that creates Boot's defaultDataSource. Without it,AuditAutoConfigurationmight be processed first. The condition would then find noDataSourceand the class would be skipped. The failure would be silent. Nothing would be reported as wrong, andAuditLoggerwould simply be missing.
The same trap exists, with no order guarantee at all, if you use @ConditionalOnBean in ordinary application configuration. Scanned classes are processed in an order you do not control. A bean condition in one of them may run before the class that defines the bean it needs. The result can change when you rename a package or add a class. Boot's documentation says plainly that these two conditions should be used only on auto-configuration classes, where the order is defined.
Related conditions
Two neighbors of @ConditionalOnBean solve narrower problems.
@ConditionalOnSingleCandidatematches when exactly one bean of the type exists, or when several exist but one is marked@Primary. Use it when your configuration injects a single instance. With two unmarkedDataSourcebeans,@ConditionalOnBean(DataSource.class)matches but injection would then fail.@ConditionalOnSingleCandidate(DataSource.class)does not match, so the configuration is skipped.@ConditionalOnMissingBeancan be combined with@ConditionalOnBeanon different methods in one class. This lets you provide a default and also a variant that applies when a collaborator is present.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Your auto-configured bean never appears, and nothing fails | `@ConditionalOnBean` ran before the class that defines the needed bean | Add `after = ...` to `@AutoConfiguration`, then confirm in the `--debug` report |
| Both the default and the user bean exist | Return type of the auto-configured `@Bean` method is unrelated to the user's type | Declare the return type users are meant to replace, or set `value` explicitly |
| Default bean is registered although the user defined one | The user bean is in a child context and `search` is `CURRENT` | Use the default `SearchStrategy.ALL` unless you want that behavior |
| `@ConditionalOnMissingBean` seems ignored in application code | Used in a scanned class, so order is arbitrary | Move the logic into an auto-configuration |
| Startup fails with `BeanDefinitionOverrideException` | The back-off check was by name and the user used a different type with the same name | Match by type |
Summary of the rules
- Register defaults with
@Beanplus@ConditionalOnMissingBean. The application's bean then replaces yours without any extra setup. - The check is on bean definitions registered so far, matched by declared type. It is not a check on live objects.
- Bean conditions are dependable in auto-configuration because user configuration is parsed first and
beforeandaftercontrol the rest. - Use
@ConditionalOnBeanwhen a class needs another bean. Pair it withafterso the needed definition is registered by the time the condition runs.
Exercise
An auto-configuration class contains @ConditionalOnBean(DataSource.class) and no ordering attributes. Your application relies on the DataSource that Spring Boot's DataSourceAutoConfiguration creates. The class's beans are missing at runtime and there is no error. What is the most likely cause, and how do you fix it?
Show answer
The class was processed before DataSourceAutoConfiguration, so no DataSource definition was registered when the condition ran, and the condition did not match. Add after = DataSourceAutoConfiguration.class to @AutoConfiguration so the DataSource definition exists first. Then confirm the change in the --debug conditions report.
Exercise
A @Bean method in an auto-configuration is annotated @ConditionalOnMissingBean and returns Greeter, an interface. The application defines a bean whose declared return type is GreetingService, a class that implements Greeter. Does the auto-configured bean back off? What if the application's method instead returns an unrelated type Object?
Show answer
Yes, it backs off. The condition checks for a bean of type Greeter, and a definition declared as GreetingService is assignable to Greeter. If the application's method returns Object, the condition does not match that definition, because the declared type is not known to be a Greeter. The auto-configured bean is then registered as well.