Sub topic 5
Conditional annotations that drive the decisions
This chapter assumes you know what a bean and the application context are, and that you can write @Configuration classes with @Bean methods. It also assumes you have run a Spring Boot application. Earlier chapters showed that auto-configuration creates beans from the classpath. This chapter covers the mechanism that makes those decisions: conditional annotations.
Why conditions exist
Boot ships hundreds of auto-configuration classes. If all of them applied at once, an application with no database driver would still try to build a DataSource, and an application with its own ObjectMapper would get a second one. Each auto-configuration therefore carries conditions. A condition is a test evaluated while the context is being built. If the test fails, Spring skips the class or method it guards.
The base mechanism is Spring Framework's @Conditional annotation, which takes a Condition implementation. Boot builds on it with ready-made annotations in the org.springframework.boot.autoconfigure.condition package. You will almost always use those instead of writing a Condition yourself.
Where conditions can be placed
A condition annotation can sit in two places, and the position changes what is skipped.
- On a class: if the condition fails, the whole configuration class is skipped, including all its
@Beanmethods and any nested classes or imports. - On a
@Beanmethod: if the condition fails, only that bean is skipped.
Conditions on the class are evaluated first. A class-level failure means the method-level conditions are never examined.
The main conditions
Class conditions
@ConditionalOnClass matches when the named classes are on the classpath. @ConditionalOnMissingClass matches when they are absent.
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
public class GreetingAutoConfiguration {
// beans here
}This is how a starter's presence changes behavior. Adding a JDBC driver and a connection pool to the classpath makes the data source classes visible, so the data source auto-configuration passes its check.
There is one gotcha. On a class-level annotation you can reference the class directly, as above. On a @Bean method, or on a class that may be loaded when the library is missing, referencing the class directly can cause a NoClassDefFoundError because the annotation itself must be read. In those cases use the name attribute with a string:
@Bean
@ConditionalOnClass(name = "com.zaxxer.hikari.HikariDataSource")
public Object poolMarker() {
return new Object();
}Boot reads auto-configuration annotations through ASM (bytecode reading) before loading the class, so class-level @ConditionalOnClass with a class literal is safe in an auto-configuration. Nested configuration classes are the usual way to isolate method-level references to optional types.
Bean conditions
@ConditionalOnBean matches when a bean of the given type or name already exists in the context. @ConditionalOnMissingBean matches when it does not. @ConditionalOnSingleCandidate matches when exactly one bean of a type exists, or when several exist and one is marked @Primary.
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}When @ConditionalOnMissingBean has no arguments on a @Bean method, it uses the method's return type. This is the standard back-off pattern: Boot offers a default, and your own bean wins.
Bean conditions have an ordering requirement. They test the state of the context at the moment they are evaluated. For that reason, Boot recommends using them only on auto-configuration classes. Auto-configurations are processed after your own configuration classes, so your beans are already registered when the condition runs. In an ordinary @Configuration class the result depends on processing order and can surprise you.
Property conditions
@ConditionalOnProperty matches based on an environment property.
@Bean
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)
public GreetingService greetingService() {
return new GreetingService("Hello");
}The attributes work like this:
| Attribute | Meaning |
|---|---|
| `prefix` | Optional text put in front of each name, joined with a dot. |
| `name` or `value` | The property name or names that must be present. |
| `havingValue` | The value the property must equal. Comparison ignores case. |
| `matchIfMissing` | Whether the condition matches when the property is not set. Default `false`. |
Without havingValue, the property matches when it is set to anything except false. This is a common source of confusion. Setting greeting.enabled=no still matches, because no is not false. If you want a strict on/off switch, set havingValue = "true" explicitly.
The matchIfMissing flag decides your default. With matchIfMissing = true, a feature is on unless the user turns it off. With the default false, a feature is off until the user turns it on. Choose based on how surprising the feature would be if it appeared silently.
Resource and application-type conditions
@ConditionalOnResourcematches when a resource such asclasspath:app.confexists.@ConditionalOnWebApplicationmatches in a web application. You can narrow it withtype = SERVLETortype = REACTIVE.@ConditionalOnNotWebApplicationis the opposite.@ConditionalOnExpressionmatches when a SpEL expression evaluates to true. Use it sparingly, since the expression is a string and is hard to check.@ConditionalOnCloudPlatformmatches on a specific cloud platform.@ConditionalOnJavamatches a Java version range.
How conditions combine
Several annotations on the same element must all pass. They are combined with AND.
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@ConditionalOnWebApplication
public class WebGreetingAutoConfiguration {
}This class applies only when GreetingService is on the classpath and the application is a web application.
OR logic needs a different tool. Boot provides AnyNestedCondition, which you subclass with nested classes, each carrying one condition. AllNestedConditions and NoneNestedCondition exist for the other combinations. You attach the result with @Conditional(YourCondition.class).
The evaluation timeline
Conditions run in phases, which is why placing them correctly matters.
Class-level conditions such as @ConditionalOnClass are cheap and checked early, before the class is fully loaded. Bean-level conditions are checked later, when the bean definitions are being registered. This is why a class-level @ConditionalOnMissingBean can behave differently from the same condition on a method, and why most Boot auto-configurations put class and property tests on the class and bean tests on the methods.
Common errors
- Using
@ConditionalOnBeanin your own configuration. The result depends on the order in which Spring processes classes. Move the logic into an auto-configuration, or reconsider the design. - Referencing an optional class in a method signature. The JVM may fail to load the enclosing class. Isolate optional types in a nested static
@Configurationclass guarded by@ConditionalOnClass. - Assuming
@ConditionalOnPropertywithouthavingValuemeans "true". It matches any value exceptfalse. - Forgetting
matchIfMissing. The feature stays off when nobody sets the property, and the user wonders why nothing happens. - Expecting
@ConditionalOnMissingBeanto see beans from a later auto-configuration. It only sees what is registered so far. Ordering, covered in a later chapter, fixes this.
Reading conditions as a debugging aid
When a bean you expected is missing, read the annotations on the auto-configuration that should have created it. Ask three questions in order: is every class named by @ConditionalOnClass on the classpath, does a @ConditionalOnProperty need a property you have not set, and does a @ConditionalOnMissingBean find a bean that you or another library already defined? The conditions report, covered later, answers these questions for you, but knowing the annotations lets you predict its output.
Exercise
A @Bean method is annotated with @ConditionalOnProperty(prefix = "cache", name = "mode"). The application sets cache.mode=false. Is the bean created? What if the property is not set at all?
Show answer
With cache.mode=false the bean is not created, because without havingValue a property matches unless its value is false. If the property is not set, the bean is also not created, because matchIfMissing defaults to false. The bean exists only when cache.mode is set to some other value, such as true or redis.
Exercise
You write @ConditionalOnMissingBean on a @Bean method returning GreetingService, and the application defines its own GreetingService bean. Which bean ends up in the context, and why is it safe to place this condition in an auto-configuration but risky in a regular @Configuration class?
Show answer
Only the application's own bean exists, because the condition finds it and skips the auto-configured one. This is reliable in an auto-configuration because Boot processes auto-configurations after user configuration, so the user's bean is already registered when the condition runs. In a regular @Configuration class the outcome depends on the order in which classes are processed, so the condition may run before the other bean is registered.