Video in progress

Strong Middle 🌱 Spring

How do you write and register your own auto-configuration in Spring Boot 3?

You write an @AutoConfiguration class, put conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty on the beans, and list the class name in the META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file. The old spring.factories way doesn't work for auto-configuration in Boot 3.

📖 Answer

Say the company has an SMS library, and a service that includes it should immediately get an SmsClient bean.

@AutoConfiguration(after = JacksonAutoConfiguration.class)
@ConditionalOnClass(SmsClient.class)
@EnableConfigurationProperties(SmsProperties.class)
public class SmsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "sms", name = "enabled", havingValue = "true", matchIfMissing = true)
    SmsClient smsClient(SmsProperties props, RestClient.Builder builder) {
        return new SmsClient(builder.baseUrl(props.baseUrl()).build(), props.apiKey());
    }
}
# src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
uz.company.sms.autoconfigure.SmsAutoConfiguration

A few rules:

  • Keep it out of component scan. If the auto-configuration class is inside the application's package, it's loaded like an ordinary @Configuration and the conditions don't work in the expected order.
  • @ConditionalOnMissingBean is respect for the user. If the service declares its own SmsClient, yours steps aside.
  • Order. If you rely on a bean created by another auto-configuration, say so with after = ....
  • @ConditionalOnClass goes at the class level, so that no NoClassDefFoundError appears when the library is an optional dependency.

ApplicationContextRunner is very handy for testing:

new ApplicationContextRunner()
    .withConfiguration(AutoConfigurations.of(SmsAutoConfiguration.class))
    .withPropertyValues("sms.enabled=false")
    .run(ctx -> assertThat(ctx).doesNotHaveBean(SmsClient.class));

Usually the library is split into two modules: ...-autoconfigure (the configuration) and ...-starter (just the bundle of dependencies).