Sub topic 11
Writing Your Own Auto-Configuration
This chapter walks through building a small auto-configuration for a library class. It assumes you know Spring beans and the application context, @Configuration and @Bean, and basic Maven or Gradle usage. You should also have read the earlier chapters on conditional annotations, @ConfigurationProperties, and registration through AutoConfiguration.imports. Here those pieces come together in one working module.
What you are building
You will write a library module that exposes a GreetingService. Any application that puts the module on its classpath gets a ready-made GreetingService bean. The application can change the greeting text with a property, or replace the bean with its own.
The module has four parts:
- The plain library class,
GreetingService. - A properties class,
GreetingProperties, that binds thegreeting.*properties. - The auto-configuration class,
GreetingAutoConfiguration, that creates the bean. - A registration file that tells Boot the auto-configuration exists.
Step 1: The library class
The service is an ordinary class. It does not use any Spring annotation. Keeping the library free of Spring annotations lets people use it without Boot, and it means the auto-configuration decides when the object is created.
public class GreetingService {
private final String message;
public GreetingService(String message) {
this.message = message;
}
public String greet(String name) {
return message + ", " + name + "!";
}
}Step 2: Properties with defaults
@ConfigurationProperties binds properties that start with a prefix onto a class. The field initializer supplies the default. If the user sets nothing, message stays "Hello".
@ConfigurationProperties(prefix = "greeting")
public class GreetingProperties {
private String message = "Hello";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}A user can now write this in application.properties:
greeting.message=WelcomeBoot uses the setter to bind the value. Relaxed binding also accepts forms such as GREETING_MESSAGE from environment variables.
Step 3: The auto-configuration class
This class is the core of the module.
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}Each annotation has a job.
| Annotation | Purpose |
|---|---|
| `@AutoConfiguration` | Marks the class as an auto-configuration. It is a specialized `@Configuration` that Boot treats as a candidate to be loaded after user configuration. It also allows `before`, `after`, and `name` attributes for ordering. |
| `@ConditionalOnClass(GreetingService.class)` | Applies the whole class only if `GreetingService` is on the classpath. |
| `@EnableConfigurationProperties` | Registers `GreetingProperties` as a bean and binds it, so it can be injected. |
| `@ConditionalOnMissingBean` | Creates the bean only if the application context has no `GreetingService` bean yet. This is the back-off. |
Why `@ConditionalOnMissingBean` matters
Without it, a user who defines their own GreetingService would end up with two beans of the same type. Injection by type would then fail with a NoUniqueBeanDefinitionException. With the condition, the user's bean wins and yours is skipped.
For this to work, your auto-configuration must be processed after the user's own configuration. Boot guarantees this for classes registered as auto-configurations, because it defers them until all regular @Configuration classes are processed. That is why you must register the class as an auto-configuration. If you put the same class under component scanning, the ordering guarantee is lost and the condition may evaluate too early.
Choosing the right condition
@ConditionalOnMissingBean with no arguments uses the return type of the @Bean method, which is GreetingService here. You can also name the type explicitly, such as @ConditionalOnMissingBean(GreetingService.class). Two further conditions often accompany it:
@ConditionalOnProperty(prefix = "greeting", name = "enabled", matchIfMissing = true)lets users switch the feature off withgreeting.enabled=false.matchIfMissing = truekeeps it on when the property is absent.@ConditionalOnBeanrequires another bean to exist first. Use it carefully, since it depends on registration order.
A common pattern is to put @ConditionalOnProperty on the class so that one switch disables the entire configuration.
Step 4: Register the auto-configuration
Boot finds auto-configurations through a file in your jar. Create this path under src/main/resources:
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsThe file contains one fully qualified class name per line:
com.example.greeting.GreetingAutoConfigurationLines starting with # are comments. Blank lines are ignored. When the application starts, @EnableAutoConfiguration (inside @SpringBootApplication) reads every file with this name on the classpath and treats each listed class as a candidate. Each candidate is then filtered by its conditions.
Step 5: Build configuration metadata
Users get IDE completion for greeting.message only if the module ships metadata. Add the configuration processor as an optional dependency in Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>At compile time it generates META-INF/spring-configuration-metadata.json from your @ConfigurationProperties classes. Javadoc comments on the fields become the property descriptions shown in the IDE. The metadata does not change runtime behavior, but it makes the module usable without reading source code.
Your module also needs Spring Boot's auto-configuration support on its compile classpath:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>Mark any library you only want to detect, not force on users, as optional. Then @ConditionalOnClass can test for it without the module pulling it onto every application's classpath.
Step 6: Test it with `ApplicationContextRunner`
Do not test an auto-configuration with a full @SpringBootTest. ApplicationContextRunner starts a small context for each test, so you can vary properties, beans, and classpath for every case.
class GreetingAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));
@Test
void createsDefaultBean() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(GreetingService.class);
assertThat(context.getBean(GreetingService.class).greet("Ann")).isEqualTo("Hello, Ann!");
});
}
@Test
void backsOffWhenUserDefinesBean() {
contextRunner
.withBean(GreetingService.class, () -> new GreetingService("Hi"))
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann")).isEqualTo("Hi, Ann!"));
}
}AutoConfigurations.of(...) loads the class the way Boot would, with the correct ordering. Using withConfiguration(UserConfigurations.of(...)) instead registers a class as user configuration, which runs before auto-configurations.
Add two more tests to cover the remaining behavior:
@Test
void bindsCustomMessage() {
contextRunner
.withPropertyValues("greeting.message=Welcome")
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Welcome, Ann!"));
}
@Test
void skipsWhenLibraryClassMissing() {
contextRunner
.withClassLoader(new FilteredClassLoader(GreetingService.class))
.run(context -> assertThat(context).doesNotHaveBean(GreetingService.class));
}FilteredClassLoader hides a class from the context, which lets you test the @ConditionalOnClass path without building a second project.
Step 7: Check it in a real application
Add your module as a dependency of a Boot application and start it with --debug:
java -jar app.jar --debugLook in the conditions evaluation report for GreetingAutoConfiguration. Under "Positive matches" you should see the @ConditionalOnClass and @ConditionalOnMissingBean lines. If you defined your own GreetingService, the report lists the bean method under "Negative matches" with a message that a bean of that type was found. If the class is not listed at all, the registration file is the usual cause.
Common errors
| Symptom | Likely cause |
|---|---|
| Bean is never created and the class is absent from the report | The `.imports` file is missing, misnamed, or not packaged in the jar. |
| Two beans of the same type, and injection fails | The auto-configuration was component-scanned, or `@ConditionalOnMissingBean` is missing. |
| `greeting.message` has no effect | `@EnableConfigurationProperties` is missing, or there is no setter on the properties class. |
| `ClassNotFoundException` when the optional library is absent | A `@ConditionalOnClass` was placed on a `@Bean` method whose return type is that class. Put the condition on the class or on a nested configuration class instead. |
| IDE shows no property hints | The configuration processor is missing from the build. |
The ClassNotFoundException row has a mechanism worth knowing. Spring reads class annotations with ASM, without loading the classes, so @ConditionalOnClass on the outer class is safe. Method return types, however, can be loaded when the configuration class is introspected. To guard a bean whose type belongs to an optional library, put it in a static nested @Configuration class that carries its own @ConditionalOnClass.
Exercise
A teammate's auto-configuration defines a GreetingService bean with @Bean but without @ConditionalOnMissingBean. An application also defines its own GreetingService. What happens, and how do you fix it?
Show answer
The context contains two GreetingService beans, so anything that injects one by type fails with a NoUniqueBeanDefinitionException. Add @ConditionalOnMissingBean to the @Bean method so the auto-configured bean backs off when the application provides its own. Confirm the fix with a test that uses withBean(...) in ApplicationContextRunner, or check the conditions report for a negative match.
Exercise
You add com.example.greeting.GreetingAutoConfiguration to META-INF/spring.factories in a Boot 3 project, but the bean never appears. Where should the line go instead?
Show answer
Put it in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, one class name per line. Boot 3 does not read the EnableAutoConfiguration key in spring.factories.