Sub topic 3
Conditions: @Conditional and Condition
This chapter assumes you can write @Configuration and @Bean classes, run a Spring Boot application, and set properties in application.properties. You will learn the mechanism that every @ConditionalOn... annotation is built on. Once you know it, you can read any Boot condition and write your own.
Why conditions exist
An auto-configuration class ships with a library and is considered for every application that includes the library. It cannot assume the application wants everything it offers. A JDBC starter should not create a DataSource when the user already defined one, and a web configuration should not apply to a command-line tool.
Spring solves this with conditions. A condition is a test that Spring runs while it reads configuration. If the test fails, Spring skips the annotated class or method, and no bean definition is registered for it.
The @Conditional annotation
@Conditional is defined in org.springframework.context.annotation. It takes one or more classes that implement Condition:
@Conditional(MyCondition.class)You can place it in three locations:
- On a
@Configurationclass (or any@Component). When the condition fails, Spring skips the whole class: its@Beanmethods, its@Importdeclarations, and its nested configuration classes. - On a
@Beanmethod. When the condition fails, only that bean is skipped. - On another annotation, as a meta-annotation. This is how
@ConditionalOnClass,@ConditionalOnPropertyand the rest are built.
If you list several classes in one @Conditional, or place several conditional annotations on the same element, all of them must match. Conditions combine with AND, never OR.
The Condition interface
Condition has one method:
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);It returns true when the annotated element should be processed. The two parameters give the condition everything it may inspect.
| Parameter | Method | What it gives you |
|---|---|---|
| `ConditionContext` | `getEnvironment()` | Properties and active profiles |
| `ConditionContext` | `getRegistry()` | The bean definitions registered so far |
| `ConditionContext` | `getBeanFactory()` | The bean factory, which may be `null` |
| `ConditionContext` | `getResourceLoader()` | Access to files and classpath resources |
| `ConditionContext` | `getClassLoader()` | The class loader, used to test whether a class is present |
| `AnnotatedTypeMetadata` | `isAnnotated(name)` | Whether a given annotation is present |
| `AnnotatedTypeMetadata` | `getAnnotationAttributes(name)` | The attribute values of that annotation |
The AnnotatedTypeMetadata is the metadata of the element the condition sits on. For a class-level condition it describes the class, and for a @Bean method it describes the method. Annotation-based conditions use it to read their own attributes, such as the havingValue of @ConditionalOnProperty.
How a condition is evaluated
Spring evaluates conditions while it builds bean definitions, before any bean instance exists. A condition never sees a running object. It sees metadata, the environment, and whichever bean definitions have been registered at that moment.
Evaluation is lazy and ordered. A class-level failure ends the process for that class, so its method-level conditions are never run. Conditions on later classes can see the bean definitions registered by earlier ones. This is why the next chapters spend time on ordering.
Writing a custom condition
Suppose a feature should only be active when the machine has enough CPU cores. First, write the annotation that users will put on their code:
package com.example.conditions;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Conditional;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnMinimumCpusCondition.class)
public @interface ConditionalOnMinimumCpus {
/** The minimum number of available processors. */
int value();
}Then write the condition. It reads the annotation's value from the metadata and compares it with the processor count:
package com.example.conditions;
import java.util.Map;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
class OnMinimumCpusCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes =
metadata.getAnnotationAttributes(ConditionalOnMinimumCpus.class.getName());
int required = (Integer) attributes.get("value");
return Runtime.getRuntime().availableProcessors() >= required;
}
}Now use it on a bean method:
package com.example.conditions;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class WorkerConfiguration {
@Bean(destroyMethod = "shutdown")
@ConditionalOnMinimumCpus(4)
public ExecutorService parallelExecutor() {
return Executors.newFixedThreadPool(4);
}
}On a machine with fewer than four processors, Spring registers no parallelExecutor bean. Any other bean that injects it fails at startup, so consumers of conditional beans should use ObjectProvider<ExecutorService> or be conditional themselves.
Reporting why a condition matched
A plain Condition returns only true or false. When it returns false, nobody can tell why. Spring Boot adds SpringBootCondition, an abstract class whose subclasses return a ConditionOutcome with a message. Boot's own conditions extend it, and the messages are what you read in the conditions evaluation report, covered in a later chapter.
package com.example.conditions;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
class OnMinimumCpusCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes =
metadata.getAnnotationAttributes(ConditionalOnMinimumCpus.class.getName());
int required = (Integer) attributes.get("value");
int available = Runtime.getRuntime().availableProcessors();
if (available >= required) {
return ConditionOutcome.match("found " + available + " processors, need " + required);
}
return ConditionOutcome.noMatch("found " + available + " processors, need " + required);
}
}This version replaces the previous one. SpringBootCondition implements matches for you, calls getMatchOutcome, and logs the outcome. Use it for any condition you intend to ship in an auto-configuration, because the message is the only diagnostic your users get.
Rules and limits of Condition classes
A condition class must have a no-argument constructor. Spring instantiates it itself, so constructor injection does not work, and conditions are not beans. A condition may implement these callback interfaces and Spring will call them before matches:
EnvironmentAwareBeanFactoryAwareBeanClassLoaderAwareResourceLoaderAware
For anything else, read what you need from the ConditionContext.
Condition phases in brief
Conditions run at one of two points. A condition can declare its point by implementing ConfigurationCondition and returning a ConfigurationPhase:
PARSE_CONFIGURATION: evaluated while Spring parses@Configurationclasses. A failure stops Spring from processing the class at all, including its imports.REGISTER_BEAN: evaluated when Spring registers a bean definition. A failure only prevents that registration, and the class itself has already been parsed.
A plain Condition has no declared phase. Spring evaluates it at parse time when it sits on a configuration class, and at registration time when it sits on a @Bean method or another component. The distinction matters for bean-based conditions, and a later chapter covers it in detail.
Combining conditions with OR
Since multiple conditions combine with AND, you need a helper when you want OR. Spring Boot provides AnyNestedCondition for this. You write a class that extends it, add static nested classes annotated with the conditions, and use the outer class in @Conditional:
package com.example.conditions;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase;
class CacheOrMetricsCondition extends AnyNestedCondition {
CacheOrMetricsCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(prefix = "app.cache", name = "enabled", havingValue = "true")
static class CacheEnabled {
}
@ConditionalOnProperty(prefix = "app.metrics", name = "enabled", havingValue = "true")
static class MetricsEnabled {
}
}Apply it with @Conditional(CacheOrMetricsCondition.class). The condition matches when at least one nested condition matches. The constructor argument chooses the phase for the nested conditions.
Common errors
- Putting a condition on a class that component scanning finds in user code and expecting predictable results. Condition outcomes can depend on scan order, so Boot reserves bean-based conditions for auto-configurations.
- Reading
getAnnotationAttributesfor an annotation the element does not carry. The method returnsnull, and the code throws aNullPointerException. Look up your own annotation name only. - Testing for a class with
Class.forNameinside a condition and letting the class loader exception escape. Catch it, or useClassUtils.isPresent(name, context.getClassLoader()). - Expecting a method-level condition to prevent injection failures. The bean is absent, and its consumers still need it.
- Forgetting the no-argument constructor, which produces a startup error when Spring tries to instantiate the condition.
Exercise
A @Configuration class carries @ConditionalOnMinimumCpus(8), and one of its @Bean methods carries @ConditionalOnMinimumCpus(2). The machine has 4 processors. Is the bean registered, and why?
Show answer
No. Conditions are evaluated from the outside in. The class-level condition requires 8 processors and fails on a 4-processor machine, so Spring skips the whole class and never evaluates the method-level condition. The method's own condition would have matched, but it makes no difference.
Exercise
Why does OnMinimumCpusCondition extend SpringBootCondition instead of implementing Condition directly, and what must the class provide as a consequence?
Show answer
SpringBootCondition records a message with each outcome, so the conditions evaluation report can explain why the condition matched or not. A plain Condition returns only a boolean. The subclass implements getMatchOutcome and returns ConditionOutcome.match(...) or ConditionOutcome.noMatch(...) with a descriptive message.