Sub topic 7
When conditions are evaluated
This chapter assumes you know what @ConditionalOnClass, @ConditionalOnBean and @ConditionalOnMissingBean do, and that you can read a @Configuration class. The question here is when each condition runs. The answer explains two common surprises. @ConditionalOnBean can match in one project and fail in another. A @ConditionalOnMissingBean back-off can work for user beans and still fail against another auto-configuration.
Conditions run at specific points
A condition does not run when the application context starts. It runs while Spring is processing configuration classes, and it sees only what has been recorded up to that point. Spring splits this processing into two phases.
- Parse phase. Spring reads each configuration class, its annotations, its nested classes, its
@Importand@ComponentScandeclarations, and the@Beanmethods it declares. No bean definitions are registered yet for the class being read. - Register-bean phase. After parsing, Spring turns the parsed configuration classes into bean definitions. Each
@Beanmethod becomes a definition, unless a condition rules it out.
The phase is expressed by the ConfigurationCondition interface, which extends Condition. Its getConfigurationPhase() method returns either ConfigurationPhase.PARSE_CONFIGURATION or ConfigurationPhase.REGISTER_BEAN.
| Condition kind | Phase | What it can see |
|---|---|---|
| `@ConditionalOnClass`, `@ConditionalOnMissingClass` | Parse (and earlier, see below) | The classpath only |
| `@ConditionalOnProperty`, `@ConditionalOnResource`, `@ConditionalOnExpression` | Plain `Condition`, no fixed phase | The `Environment`, resources |
| `@ConditionalOnBean`, `@ConditionalOnMissingBean`, `@ConditionalOnSingleCandidate` | Register-bean | Bean definitions registered so far |
A plain Condition that does not implement ConfigurationCondition has no required phase. Spring evaluates it the first time it checks the annotated element, and that check can happen again in the later phase. This is harmless for conditions that depend on stable inputs such as the classpath and the environment. It would be a problem for conditions that depend on registered beans.
Why the phase matters
The consequence of the parse phase is that a failed condition on a class skips everything that class would have contributed. Its nested classes, its @Import declarations and its component scans are all ignored. This is why @ConditionalOnClass on an auto-configuration class is safe: Spring never tries to process @Bean methods whose return types are missing from the classpath.
The register-bean phase is what makes bean conditions possible. @ConditionalOnBean asks "does a bean definition of this type exist?" That question has no meaningful answer during parsing, because the definitions have not been created yet. So OnBeanCondition declares REGISTER_BEAN. It runs when Spring is about to register the beans of a configuration class, and it looks at the definitions already in the bean factory.
Two details follow from this:
- The condition inspects bean definitions, not bean instances. No bean has been created at this point, so Spring works out each type from the definition's metadata. For a
@Beanmethod that metadata is the method's declared return type. A method declared as returningObjector a broad interface can fail to match a@ConditionalOnBean(MyImpl.class)that you expected to match. - The condition sees only definitions registered earlier. Definitions that will be registered by a class processed later do not exist yet.
The second detail is the reason ordering matters for bean conditions.
Where auto-configuration fits in the sequence
Spring Boot loads auto-configuration classes through a deferred import selector. "Deferred" means the selected classes are processed after all the other configuration classes in the application have been parsed. The sequence is:
- Your own configuration classes and component-scanned classes are parsed.
- The candidates from
AutoConfiguration.importsare filtered and parsed, in their sorted order. - Bean definitions are registered, class by class. Each class's register-bean conditions are checked just before its
@Beanmethods are registered.
Because user configuration is parsed before the auto-configuration candidates, @ConditionalOnMissingBean in an auto-configuration reliably sees your beans. That is the mechanism behind back-off. Among auto-configurations, the sorted order from step 4 decides who sees whom.
Class conditions can run even earlier
The class-condition annotations get one more optimization. Before parsing, Spring Boot runs AutoConfigurationImportFilter implementations over the candidate list. OnClassCondition is one of these filters. It reads the @ConditionalOnClass values from the class files' annotation metadata without loading the classes. It removes candidates whose required classes are absent.
Two practical effects follow:
- Startup is faster, because Spring never parses auto-configurations for libraries that are not on the classpath.
@ConditionalOnClassshould name classes withvalue = X.classonly on a class-level annotation. On a@Beanmethod, a missing class can cause aNoClassDefLoadError, because the method signature may reference it. Put the condition on a nested@Configurationclass, or use thename = "fully.qualified.Name"attribute, which takes a string.
package com.example.audit;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MetricsAuditConfiguration {
// Safe: the nested class is skipped when the class is missing,
// so its @Bean method signature is never resolved.
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "io.micrometer.core.instrument.MeterRegistry")
static class MicrometerSupport {
@Bean
AuditMetrics auditMetrics(io.micrometer.core.instrument.MeterRegistry registry) {
return new AuditMetrics(registry);
}
}
}AuditMetrics here stands for a class in your project that takes a MeterRegistry. The name form lets the outer class load even when Micrometer is absent.
A bean condition that depends on order
The audit example from this tutorial's plan shows the dependency directly.
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);
}
}@ConditionalOnBean(DataSource.class) is checked when this class is about to register its beans. If DataSourceAutoConfiguration registered its DataSource definition earlier, the condition matches. Without after = DataSourceAutoConfiguration.class, the result depends on the default sort. That sort is alphabetical by class name, adjusted by @AutoConfigureOrder and by other classes' before and after values. A change such as renaming a class or adding a dependency can then flip the result, and nothing in the code would explain why. The after attribute removes that fragility. The next chapter covers ordering in detail.
Application-level configuration is a different case. The order of user @Configuration classes is not something you control well. Spring Boot's documentation advises using @ConditionalOnBean and @ConditionalOnMissingBean only in auto-configuration classes. In your own configuration classes, prefer explicit @Import or plain beans.
Writing a condition with an explicit phase
If you write your own condition that inspects bean definitions, implement ConfigurationCondition and declare the register-bean phase. Otherwise the condition might run during parsing, before any definitions exist.
package com.example.audit;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.core.type.AnnotatedTypeMetadata;
class OnDataSourceDefinitionCondition implements ConfigurationCondition {
@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// includeNonSingletons = true, allowEagerInit = false:
// look at definitions only, do not create any beans.
return context.getBeanFactory()
.getBeanNamesForType(javax.sql.DataSource.class, true, false).length > 0;
}
}Apply it with @Conditional(OnDataSourceDefinitionCondition.class). Passing false for allowEagerInit keeps the check from triggering early creation of factory beans. Early creation is the kind of side effect that makes startup problems hard to trace.
Common mistakes
- Expecting
@ConditionalOnBeanto see a bean created later. The condition checks definitions registered so far. A definition added by a class sorted after yours is invisible to it. - Declaring a vague return type. A
@Beanmethod that returnsObjector a base type may not match@ConditionalOnBean(Concrete.class)or@ConditionalOnMissingBean(Concrete.class). Return the most specific type you want others to match on. - Putting
@ConditionalOnClass(X.class)on a@Beanmethod. The method signature referencesX, so a missing class can fail before the condition is checked. Use a nested configuration class or thenameattribute. - Relying on user beans seen through
@ConditionalOnMissingBeanin tests only. InApplicationContextRunneryou choose which configurations are included and in what order. A passing test does not prove the order in a real application. Pin the order withafterorbefore, and test it with the real set of auto-configurations when it matters. - Reading a property condition as bean-aware.
@ConditionalOnPropertylooks only at theEnvironment. It does not know whether any bean exists.
Exercise
An auto-configuration class is annotated @ConditionalOnBean(DataSource.class) and has no after attribute. It works on your machine but fails in a colleague's project that adds another auto-configuration library. Explain a likely cause and a fix.
Show answer
@ConditionalOnBean runs in the register-bean phase and only sees bean definitions registered by classes processed earlier. Without after, the position of your class relative to the one that registers the DataSource depends on the default sort (alphabetical, then @AutoConfigureOrder, then other classes' before and after). The extra library changed that sorted order, so your class was processed before the DataSource definition existed. The fix is @AutoConfiguration(after = DataSourceAutoConfiguration.class), which fixes your class's position after the one that registers the DataSource.
Exercise
Why can @ConditionalOnMissingBean in an auto-configuration reliably detect a bean defined in the application's own @Configuration class?
Show answer
Auto-configuration classes are imported through a deferred import selector, so they are parsed after the application's own configuration classes. By the time an auto-configuration's bean method is checked, the user's bean definitions are already registered and the condition sees them, so the auto-configured bean backs off.
Exercise
Why should a custom condition that looks for registered bean definitions implement ConfigurationCondition and return REGISTER_BEAN?
Show answer
A plain Condition has no required phase, so Spring can evaluate it during the parse phase, before bean definitions exist, and it would see an incomplete or empty set. Returning REGISTER_BEAN makes Spring evaluate it only when it is about to register the beans of the class, after parsing, when earlier definitions are present.