Sub topic 10
Controlling Auto-Configuration Order
Prerequisites
This chapter assumes you know how @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnBean work, and that you can register a class in AutoConfiguration.imports. It also assumes you have written a basic auto-configuration like the GreetingAutoConfiguration from earlier chapters.
Why order matters
Boot evaluates conditions while it registers bean definitions, one configuration class at a time. A condition such as @ConditionalOnBean(DataSource.class) looks at the bean definitions registered so far. If the auto-configuration that defines the DataSource has not been processed yet, the condition sees nothing and your bean is silently skipped.
The same applies to @ConditionalOnMissingBean. If your auto-configuration runs before another one that defines the same type, both beans can be registered, or the wrong one can win.
Order is therefore the way you tell Boot which decisions must be made first.
What ordering does and does not control
Ordering is narrower than it first appears.
- It controls the order in which auto-configuration classes are processed, and so the order in which their bean definitions are registered and their conditions are evaluated.
- It does not control the order in which beans are created. Bean creation follows dependencies. If one bean must be created before another without a constructor or field dependency, use
@DependsOn. - It does not control the order of beans injected as a
List<T>. That order comes from@Orderor theOrderedinterface on the beans, which is a separate mechanism. - It applies only to auto-configurations. User configuration classes found by component scanning are always processed before auto-configurations. This is why your own beans can make auto-configuration back off.
Because of the last point, @ConditionalOnBean and @ConditionalOnMissingBean are reliable only in auto-configuration classes. On ordinary @Configuration classes the result depends on processing order, which you cannot easily control.
The ordering tools
Boot gives you two kinds of ordering: relative and absolute.
| Tool | Kind | Use it when |
|---|---|---|
| `@AutoConfiguration(after = ...)` | Relative | Your class depends on beans from another auto-configuration. |
| `@AutoConfiguration(before = ...)` | Relative | Your class must define beans before another one checks for them. |
| `afterName` and `beforeName` | Relative, by class name | The other class may not be on the classpath. |
| `@AutoConfigureOrder(n)` | Absolute | Two auto-configurations should run early or late without knowing about each other. |
@AutoConfigureBefore and @AutoConfigureAfter are the older standalone annotations. They behave the same as the before and after attributes of @AutoConfiguration, and you can still see them in older code.
Relative ordering with before and after
Use a class reference when the other class is always present, and a name when it might not be:
@AutoConfiguration(
after = DataSourceAutoConfiguration.class,
beforeName = "com.example.optional.ReportingAutoConfiguration")
public class AuditAutoConfiguration {
}If you reference a class that is not on the classpath through a class literal, the reference can fail to load. A string name is safe because Boot only compares names. When you are not sure the target library is present, use the Name variants.
Absolute ordering with @AutoConfigureOrder
@AutoConfigureOrder takes an integer, the same scale used by Ordered. The default is 0, and lower numbers run first.
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 {
}Reserve this for infrastructure that must come first or last. For ordinary dependencies between two specific classes, relative ordering says what you mean and survives other changes.
How Boot sorts the list
Boot sorts the candidates from AutoConfiguration.imports in three passes. The later passes take priority over the earlier ones.
- Sort alphabetically by fully qualified class name. This gives a stable starting order.
- Sort by
@AutoConfigureOrder. Classes with equal values keep their alphabetical order. - Apply
beforeandafterconstraints. A class is moved after everything it must follow.
This explains a common surprise. An auto-configuration with no ordering annotations still has a deterministic position, but only by accident of its class name. Renaming or moving a package can change that position and break a condition that worked before. If your class depends on another one, say so explicitly.
Worked example: an audit bean that needs a DataSource
Suppose a library offers an AuditLog that writes events to a table. It should be created only when the application has a DataSource.
The library class:
import org.springframework.jdbc.core.JdbcTemplate;
public class AuditLog {
private final JdbcTemplate jdbc;
public AuditLog(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public void record(String event) {
jdbc.update("insert into audit(event) values (?)", event);
}
}Without ordering, the auto-configuration is fragile:
// Fragile: no ordering relative to DataSourceAutoConfiguration
@AutoConfiguration
public class AuditAutoConfiguration {
@Bean
@ConditionalOnBean(DataSource.class)
public AuditLog auditLog(DataSource dataSource) {
return new AuditLog(new JdbcTemplate(dataSource));
}
}Whether this works depends on where AuditAutoConfiguration falls relative to DataSourceAutoConfiguration. A package named com.example.audit sorts before org.springframework..., so the condition would run first, find no DataSource, and skip the bean. The fix is to declare the dependency:
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.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnClass(JdbcTemplate.class)
public class AuditAutoConfiguration {
@Bean
@ConditionalOnBean(DataSource.class)
@ConditionalOnMissingBean
public AuditLog auditLog(DataSource dataSource) {
return new AuditLog(new JdbcTemplate(dataSource));
}
}Now DataSourceAutoConfiguration is always processed first, so the DataSource definition exists when @ConditionalOnBean runs. Register the class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:
com.example.audit.AuditAutoConfigurationThe registration is not optional. Ordering applies only to classes that Boot loads from the imports file. If the class is picked up another way, such as component scanning, before and after are ignored.
Testing the order
ApplicationContextRunner can check that the ordering works. The AutoConfigurations.of(...) helper applies the same sorting rules as the real application, so you can list classes in any order and still get the production order.
This test needs H2 and spring-jdbc on the test classpath, plus JUnit and AssertJ.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class AuditAutoConfigurationTests {
@Test
void createsAuditLogWhenDataSourceExists() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
AuditAutoConfiguration.class,
DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.url=jdbc:h2:mem:audit")
.run(context -> assertThat(context).hasSingleBean(AuditLog.class));
}
@Test
void backsOffWithoutDataSource() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class))
.run(context -> assertThat(context).doesNotHaveBean(AuditLog.class));
}
}The first test lists AuditAutoConfiguration before DataSourceAutoConfiguration on purpose. It passes only because the after attribute reorders them. Remove after and run it again to see it fail.
If you register classes with withUserConfiguration(...) instead, no sorting happens and the classes are processed in the order you give. Use that form when you want to test a specific order directly.
Diagnosing order problems
Order bugs usually appear as a bean that is missing even though the library is present. Start the application with --debug and read the conditions report. For the audit example, the failing version would show something like this under negative matches:
AuditAutoConfiguration#auditLog:
Did not match:
- @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans of type javax.sql.DataSourceIf the report says no bean of that type was found, but you can see the bean listed as a positive match elsewhere in the same report, the cause is almost always order. Add after for the class that defines the bean.
Failure modes
- Cycles. If class A is
afterB and B isafterA, directly or through a chain, Boot fails at startup with anIllegalStateExceptionthat reports an "AutoConfigure cycle detected" between the two classes. Remove one of the constraints. - Ordering a class that is not registered. Constraints on classes missing from the imports file have no effect, and constraints that name absent classes are simply ignored.
- Overusing
@AutoConfigureOrder. Two libraries that both claimHIGHEST_PRECEDENCEfall back to alphabetical order between themselves. Preferbeforeandafterfor real dependencies. - Using
@Orderon an auto-configuration.@Orderhas no effect on the processing order of configuration classes. Use@AutoConfigureOrder. - Expecting bean creation order. After the ordering is fixed, beans are still created by dependency order. Use constructor injection or
@DependsOnfor that.
Exercises
Exercise
A custom auto-configuration declares @ConditionalOnBean(DataSource.class) on a bean method. The conditions report shows the condition did not find any DataSource, yet DataSourceAutoConfiguration appears under positive matches. What is the likely cause, and what is the fix?
Show answer
The custom class is processed before DataSourceAutoConfiguration, so the DataSource definition does not exist yet when the condition runs. Add after = DataSourceAutoConfiguration.class to its @AutoConfiguration annotation, and make sure the class is listed in AutoConfiguration.imports.
Exercise
You added @AutoConfiguration(after = SomeOtherAutoConfiguration.class) to a class, but the ordering has no effect. The class is in a package under your application's @SpringBootApplication class. Why, and what do you change?
Show answer
Component scanning picks the class up as an ordinary configuration, which is processed before the auto-configuration phase, so before and after are ignored. Move it to a package outside the scanned packages, such as the library's own package, and register it in AutoConfiguration.imports.
Exercise
What is the difference between the order in which auto-configurations are processed and the order in which beans are created? Which annotation would you use to force one bean to be created before another that does not depend on it?
Show answer
Processing order controls when bean definitions are registered and conditions are evaluated. Creation order follows bean dependencies once the definitions exist. Use @DependsOn on the bean that must wait for the other.