Sub topic 3
Conditions: @Conditional and Condition
This chapter assumes you know @Configuration and @Bean classes, and that you can run a basic Spring Boot application. Every auto-configuration decision in Spring Boot rests on the mechanism described here.
The idea
An auto-configuration class is only useful if it can stay out of the way. It must not create a database pool when no database driver is present, and it must not replace a bean you wrote yourself. Spring solves this with conditions. A condition is a yes-or-no test that Spring runs before it registers a bean definition. If the test says no, the definition is skipped and no bean is created.
Two types make this work:
Conditionis an interface with one method,matches, that returnstrueorfalse.@Conditionalis an annotation that names one or moreConditionclasses. It goes on a@Configurationclass, a@Beanmethod, or another annotation.
All the @ConditionalOnXxx annotations that Spring Boot ships are built on these two types.
How a condition is evaluated
When you list several conditions, all of them must match. A condition on a @Configuration class gates the whole class, including every @Bean method inside it. A condition on a single @Bean method gates only that method.
Writing a Condition
The matches method receives two arguments:
ConditionContextgives access to theEnvironment, theBeanFactory, theResourceLoaderand theClassLoader.AnnotatedTypeMetadatadescribes the annotations on the class or method being tested.
This condition matches only when the property feature.verbose is true:
package com.example.demo;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class VerboseCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment()
.getProperty("feature.verbose", Boolean.class, false);
}
}Apply it with @Conditional:
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class VerboseConfiguration {
@Bean
@Conditional(VerboseCondition.class)
public String verboseMarker() {
return "verbose mode is on";
}
}Start the application with --feature.verbose=true and a String bean named verboseMarker exists. Without the property, the bean is never defined.
Where Spring Boot's conditions come from
You rarely write a Condition by hand. Spring Boot's conditions follow the same pattern: each @ConditionalOnXxx annotation is meta-annotated with @Conditional and points to a condition class, for example OnPropertyCondition. These classes extend SpringBootCondition, which records why each test passed or failed. That record is what you read later in the conditions report.
| Annotation | Question it asks |
|---|---|
| `@ConditionalOnClass` | Is this class on the classpath? |
| `@ConditionalOnMissingBean` | Has nobody defined a bean of this type yet? |
| `@ConditionalOnProperty` | Does this property have the expected value? |
The following chapters cover each of these in detail.
Common errors
- Reading beans in
matchestoo early. Conditions run while Spring is still building bean definitions, socontext.getBeanFactory()only reflects definitions registered so far. A condition that checks for a bean can give different answers depending on processing order. The later chapters on bean conditions and ordering cover this. - Instantiating beans inside a condition. Don't call
getBeanthere. Inspect definitions or the environment instead. - Throwing from
matches. An exception stops the application from starting. Returnfalsewhen the information you need is missing. - Expecting a condition to remove a bean you registered another way.
@Conditionalonly gates the class or method it sits on.
Exercise
A @Configuration class has @Conditional(VerboseCondition.class) on the class and three @Bean methods, one of which has its own @Conditional(OtherCondition.class). VerboseCondition returns true and OtherCondition returns false. Which of the three beans are registered?
Show answer
Two. The class-level condition passes, so the two unconditioned @Bean methods are registered. The method with OtherCondition is skipped because its own condition returned false.