Sub topic 8
Controlling auto-configuration order
This chapter assumes you know Spring @Configuration and @Bean classes, have run a basic Spring Boot application, and have read the earlier chapters on @Conditional, @ConditionalOnBean and @ConditionalOnMissingBean. Here you will see why the order in which auto-configurations are processed changes what a condition can see, and how to control that order.
Why order matters
An auto-configuration class contributes bean definitions to the application context. Spring processes these classes one after another. Conditions such as @ConditionalOnBean and @ConditionalOnMissingBean look at the bean definitions registered so far. They do not look ahead at classes that have not been processed yet.
This means the same condition can give different answers depending on where its class sits in the sequence. Consider this question: "Is there a DataSource bean?" If the class that defines the DataSource has already been processed, the answer is yes. If it has not, the answer is no, even though the bean will exist once startup finishes.
Conditions that only look at the classpath or at properties, such as @ConditionalOnClass and @ConditionalOnProperty, do not depend on order. Their answer does not change as bean definitions are registered. Order matters for the bean conditions.
The default order
If you do nothing, Spring Boot does not guarantee a useful order between your auto-configurations. The candidates come from the AutoConfiguration.imports files, and Boot sorts them. It first sorts them alphabetically by class name. It then applies any ordering you have declared with before, after, or @AutoConfigureOrder.
Alphabetical order is an accident, not a design. If you depend on it, a rename can break your application. Declare the order you need.
Auto-configurations as a group are also processed after the application's own configuration classes. This is why @ConditionalOnMissingBean works as a back-off. The user's beans are already registered when the auto-configuration is evaluated.
Declaring order with before and after
The @AutoConfiguration annotation has two attributes for ordering:
afternames auto-configurations that must be processed before this one.beforenames auto-configurations that must be processed after this one.
Each attribute accepts class literals. A string version is available as afterName and beforeName, for classes that may not be on the classpath. Using a string avoids a compile-time dependency on the other class.
This example from the topic plan uses after:
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);
}
}DataSourceAutoConfiguration registers the DataSource definition. Because AuditAutoConfiguration is processed after it, the @ConditionalOnBean(DataSource.class) check can see that definition. Without after, the result would depend on the default order, and the condition could fail even though a DataSource exists.
Using afterName for optional classes
If the class you want to order against may be absent, a class literal would fail to compile or load. Use the name form instead:
package com.example.audit;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
@AutoConfiguration(afterName = "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration")
public class NamedOrderAutoConfiguration {
@Bean
public String namedOrderMarker() {
return "ordered";
}
}If the named class is not present, Spring Boot ignores that ordering entry. The constraint only applies when both classes are candidates.
before versus after
Both attributes express the same kind of relationship from different sides. "A is after B" and "B is before A" mean the same thing. Choose the one that lets you edit only your own class.
- Use
afterwhen your class needs to see beans from another class. This is the common case for@ConditionalOnBean. - Use
beforewhen your class must register something first, so that another auto-configuration backs off or sees it. You can only addbeforeto your own class, so it is how you affect classes you do not control.
For example, a library that wants to supply its own DataSource and stop the default one from being created could declare before = DataSourceAutoConfiguration.class. Its bean is then registered first, and the default DataSource definition backs off through @ConditionalOnMissingBean.
A coarse option: @AutoConfigureOrder
@AutoConfigureOrder assigns a numeric order, similar to Spring's @Order. Lower numbers are processed earlier. It is useful when you want a class to run near the start or end without naming specific neighbors.
package com.example.audit;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.core.Ordered;
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class EarlyAutoConfiguration {
}Prefer before and after when you know which class you depend on. They state the reason for the order. A bare number does not.
Boot applies the sorting in three steps. First alphabetical order, then @AutoConfigureOrder, then before and after. The relative constraints are applied last, so they win when they conflict with a number.
How the sort behaves
The ordering constraints form a graph. Each after or before is an edge between two classes. Boot sorts the candidates so that every edge is respected.
Because the constraints are edges in a graph, they can contradict each other. If A must come after B and B must come after A, no valid order exists. Spring Boot detects this and fails at startup with an error that names a circular reference. The fix is to remove or reverse one constraint.
What ordering does not do
Ordering affects when a class is processed. It does not change when beans are created. Bean creation follows dependency injection, not the processing order. Two points follow from that:
- Use
@DependsOnor constructor injection to control bean creation. Do not use auto-configuration order for this. - Ordering has no effect on a class that is not applied. If a
@ConditionalOnClassfails, the class is skipped and its position no longer matters.
Order also does not apply to ordinary application @Configuration classes in the same way. User configuration is processed before all auto-configuration. You cannot place an auto-configuration before the user's own classes.
Why @ConditionalOnBean belongs in auto-configuration
Because of the ordering rules, Spring Boot's documentation advises using @ConditionalOnBean and @ConditionalOnMissingBean only in auto-configuration classes. In your application's own configuration, you cannot rely on the processing order between your classes. A @ConditionalOnBean there may silently fail because the bean it wants has not been registered yet.
In auto-configuration, you get two guarantees. The user's own beans are already registered, and you can pin the order relative to other auto-configurations with before and after. That makes the result predictable.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Using `@ConditionalOnBean` without `after` | Bean is missing, but only sometimes, depending on class names | Add `after` for the class that defines the bean |
| Referring to an optional class with a class literal | `ClassNotFoundException` or `NoClassDefFoundError` at startup | Use `afterName` or `beforeName` |
| Declaring contradicting constraints | Startup fails with a circular reference error | Remove one of the constraints |
| Using order to control bean creation | Beans are still created in dependency order | Use injection or `@DependsOn` |
| Relying on alphabetical order | Works until a class is renamed | Declare `before` or `after` |
Checking the result
You can confirm the order with the conditions report. Start the application with --debug:
java -jar app.jar --debugIn the report, a failed @ConditionalOnBean appears under negative matches with a message like "did not find any beans of type". If the bean exists in the final context but the condition failed, an ordering problem is the likely cause. Add an after constraint and run again. A later chapter covers reading the full report.
Exercise
An auto-configuration class is annotated with @ConditionalOnBean(DataSource.class) and defines a bean that uses the DataSource. The application has a working DataSource, but the bean is never created, and the conditions report shows "did not find any beans of type DataSource". What is the most likely cause, and how do you fix it?
Show answer
The class is processed before DataSourceAutoConfiguration, so the DataSource definition is not registered yet when the condition is evaluated. Add after = DataSourceAutoConfiguration.class to its @AutoConfiguration annotation so it is processed afterward.
Exercise
Your library must stop a default bean from being created by another auto-configuration, which uses @ConditionalOnMissingBean. You cannot edit the other class. Which attribute do you add to your own class, and why?
Show answer
Add before (naming the other class) to your @AutoConfiguration. Your bean definition is then registered first, so the other class sees it and backs off through @ConditionalOnMissingBean.