Writing your own auto-configuration
Package shared setup as a starter so every service gets it by adding one dependency.
Open this lesson in the learning hubKey points
- An auto-configuration is an ordinary
@AutoConfigurationclass listed in a file inside your jar. - The file is
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, one class per line. - Guard every bean with
@ConditionalOnClassand@ConditionalOnMissingBeanso the application always wins. - Auto-configurations are applied after user beans, which is exactly what makes the missing-bean check work.
- Expose settings through
@EnableConfigurationPropertiesso users configure your starter from their own YAML. - Name the module
something-spring-boot-starter: thespring-boot-starter-prefix is reserved for the Boot team.
Example
// src/main/java/com/acme/sms/SmsAutoConfiguration.java
@AutoConfiguration
@ConditionalOnClass(SmsClient.class)
@EnableConfigurationProperties(SmsProperties.class)
public class SmsAutoConfiguration {
@Bean
@ConditionalOnMissingBean // the application can always override this
SmsClient smsClient(SmsProperties props) {
return SmsClient.builder()
.endpoint(props.endpoint())
.timeout(props.timeout())
.build();
}
}
@ConfigurationProperties(prefix = "acme.sms")
record SmsProperties(URI endpoint, @DefaultValue("2s") Duration timeout) { }
// src/main/resources/META-INF/spring/
// org.springframework.boot.autoconfigure.AutoConfiguration.imports
//
// com.acme.sms.SmsAutoConfiguration
// The consuming application then writes nothing but:
// acme.sms.endpoint: https://sms.internal/v1
Your own starter is the same three ingredients Boot uses: an imports file, conditions, and typed properties.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.