When to use Spring @ConfigurationCondition vs. @Condition?
java, spring
Solution
`ConfigurationCondition` is a specialization of `Condition` for `@Configuration` classes.
Plain `Condition` is just fine for 99% of your use cases so you should consider that first. The specialization is really about determining in which phase of the processing of `@Configuration` classes the condition should be evaluated.
There are two phases:
- `PARSE_CONFIGURATION` evaluates the condition when the `@Configuration`-annotated class is parsed. This gives a chance to fully exclude the configuration class
- `REGISTER_BEAN` evaluates the condition when a bean from a configuration class is registered. This does not prevent the configuration class to be added but it allows to skip a bean definition if the condition does not match (as defined by the `matches` method of the `Condition` interface)
Spring Boot has a `OnBeanCondition` that basically checks during the registration phase if another bean is present. This is the core of `ConditionalOnBean` that basically does something when a bean is present
Problem
Spring 4 has two new annotations `@Condition` and `@ConfigurationConditon` for controlling whether a bean is added to the spring application context. The JavaDoc does not provide enough context / big picture to understand the use cases for `@ConfigurationCondition`. When should `@ConfigurationCondition` be used vs. `@Condition`? ``` public interface ConfigurationCondition extends Condition { /** * Returns the {@link ConfigurationPhase} in which the condition should be evaluated. */ ConfigurationPhase getConfigurationPhase(); /** * The various configuration phases where the condition could be evaluated. */ public static enum ConfigurationPhase { /** * The {@link Condition} should be evaluated as a {@code @Configuration} class is * being parsed. * * <p>If the condition does not match at this point the {@code @Configuration} * class will not be added. */ PARSE_CONFIGURATION, /** * The {@link Condition} should be evaluated when adding a regular (non * {@code @Configuration}) bean. The condition will not prevent * {@code @Configuration} classes from being added. * * <p>At the time that the condition is evaluated all {@code @Configuration}s * will have been parsed. */ REGISTER_BEAN } } ```