Sub topic 10
Writing your own auto-configuration
This chapter assumes you can write @Configuration and @Bean classes, run a basic Spring Boot application, and set values in application.properties. You also need to know what the conditions @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty do. Earlier chapters covered them.
Here you put those pieces together. You will build a small greeting library that configures itself when a Spring Boot application includes it. The auto-configuration will:
- switch itself off with a property,
- back off when the application defines its own bean, and
- bind its settings from
application.properties.
What the library provides
A library that ships auto-configuration usually has three parts: the code it offers, a properties class, and the auto-configuration class that wires them together. The code it offers is a plain class with no Spring annotations:
package com.example.greeting;
public class GreetingService {
private final String message;
public GreetingService(String message) {
this.message = message;
}
public String greet(String name) {
return message + ", " + name + "!";
}
}Keep library classes free of Spring stereotypes such as @Component. If they carried those annotations, component scanning in the user's application could pick them up and bypass your conditions.
A library module needs spring-boot-autoconfigure on its classpath. The configuration processor is optional. It generates metadata so IDEs can suggest your property names.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>Typed settings
The properties class binds everything under the greeting prefix. It supplies a default, so the library works with no configuration at all.
package com.example.greeting;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "greeting")
public class GreetingProperties {
private String message = "Hello";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}With this class, greeting.message=Welcome in the application's application.properties changes the greeting. Without it, the message is Hello.
The auto-configuration class
package com.example.greeting;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}Each annotation does one job:
| Annotation | Level | Effect |
|---|---|---|
| `@AutoConfiguration` | Class | Marks the class as an auto-configuration. It is a specialised `@Configuration` and also carries the `before` and `after` ordering attributes. |
| `@ConditionalOnClass` | Class | Skips the whole class when `GreetingService` is not on the classpath. |
| `@ConditionalOnProperty` | Class | Skips the whole class when `greeting.enabled` is anything other than `true`. `matchIfMissing = true` means an absent property counts as a match. |
| `@EnableConfigurationProperties` | Class | Registers `GreetingProperties` as a bean and binds it. |
| `@ConditionalOnMissingBean` | Method | Creates the bean only if no `GreetingService` bean is already defined. The bean type is inferred from the method's return type. |
@AutoConfiguration has one behavior worth knowing: it does not enable component scanning. Auto-configuration classes should declare their beans explicitly with @Bean methods or imports.
Registering the class
Writing the class is not enough. Spring Boot only considers classes listed in a file in your library jar. Create this file:
src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
Put one fully qualified class name per line:
com.example.greeting.GreetingAutoConfigurationWhen an application starts, @EnableAutoConfiguration (included in @SpringBootApplication) reads every file with this name on the classpath. It merges the lists and then evaluates each candidate's conditions.
Why the back-off works
@ConditionalOnMissingBean is only reliable if the user's own bean definitions are registered before your condition runs. Spring Boot guarantees this: auto-configuration classes are processed after all user-defined configuration. That ordering is why this condition belongs in auto-configuration and not in ordinary @Configuration classes. In an ordinary class, the result would depend on whichever class happened to be processed first.
A user overrides your default by declaring a bean:
@Bean
GreetingService greetingService() {
return new GreetingService("Howdy");
}Your method is then skipped, and the user's bean is the only GreetingService.
Depending on another auto-configuration
Sometimes your configuration only makes sense when another auto-configuration has registered a bean. @ConditionalOnBean checks bean definitions that exist at the moment your class is evaluated. If the class that creates the DataSource is processed after yours, your condition sees nothing and fails. You fix this with an explicit ordering attribute.
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);
}
}Because AuditAutoConfiguration is processed after DataSourceAutoConfiguration, the DataSource definition is already registered when @ConditionalOnBean runs. Register this class in the imports file too. AuditLogger is whatever class your library provides.
Use before for the opposite case. You want your class processed first so that other auto-configurations see your beans.
Testing in isolation
Starting a full application to test a conditional configuration is slow and hides the cause of failures. ApplicationContextRunner builds a lightweight context per test, so you can vary properties and beans for each case. It comes with spring-boot-starter-test.
package com.example.greeting;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class GreetingAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));
@Test
void createsDefaultBean() {
this.contextRunner.run(context -> assertThat(context).hasSingleBean(GreetingService.class));
}
@Test
void backsOffWhenDisabled() {
this.contextRunner.withPropertyValues("greeting.enabled=false")
.run(context -> assertThat(context).doesNotHaveBean(GreetingService.class));
}
@Test
void backsOffWhenUserDefinesBean() {
GreetingService custom = new GreetingService("custom");
this.contextRunner.withBean(GreetingService.class, () -> custom)
.run(context -> assertThat(context.getBean(GreetingService.class)).isSameAs(custom));
}
}AutoConfigurations.of(...) registers the class with auto-configuration ordering semantics. A plain withUserConfiguration would not, and @ConditionalOnMissingBean could then behave differently.
Write one test per condition. These three tests cover the default path, the property switch, and the back-off.
Checking the result in a real application
Add your library to a sample application and start it with the debug flag:
java -jar app.jar --debugThe conditions evaluation report lists your class under one of three headings:
- Positive matches: all conditions passed.
- Negative matches: a condition failed, and the report names which one.
- Unconditional classes: the class has no conditions.
If GreetingAutoConfiguration appears nowhere in the report, Spring Boot never loaded it. Check the imports file.
Common errors
- The class never loads. The imports file has the wrong path or filename, a typo in the class name, or sits in
src/main/javaand is not copied into the jar. The path must be exactlyMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. @ConditionalOnBeannever matches. Your class is processed before the one that registers the bean. Addafter, or reconsider whether the check belongs in your class.- The back-off does not work.
@ConditionalOnMissingBeanis placed on a class that component scanning picked up, so it runs before the user's beans are known. Keep auto-configuration classes outside the user's scanned packages and out of@ComponentScan. - A missing optional dependency crashes startup. For a class that mentions an optional library in a
@Beanmethod signature, put the dependent beans in a static nested@Configurationclass guarded by@ConditionalOnClass. Then the outer class loads even when the library is absent. - The property has no effect. The setter is missing, or the prefix does not match.
@ConfigurationPropertiesbinds through setters by default.
Summary of the design rules
- Keep library classes free of Spring stereotypes.
- Guard the class with
@ConditionalOnClassand an opt-out property. - Put
@ConditionalOnMissingBeanon every bean a user might want to replace. - Bind settings with
@ConfigurationPropertiesand give every property a default. - Register the class in the
.importsfile. - Use
afterorbeforewhen a condition depends on beans from another auto-configuration. - Cover each condition with an
ApplicationContextRunnertest.
Exercise
A teammate adds GreetingAutoConfiguration to their library but forgets the .imports file. The class is annotated with @AutoConfiguration and sits in the library jar. The application depends on the jar. Will the greetingService bean be created, and which --debug report heading, if any, will list the class?
Show answer
The bean will not be created. Spring Boot only considers classes listed in the AutoConfiguration.imports file, and @AutoConfiguration alone does not register the class. The class will appear under no heading in the conditions report (not positive matches, not negative matches, and not unconditional classes), because it was never a candidate.
Exercise
You add @ConditionalOnBean(DataSource.class) to AuditAutoConfiguration but leave out after = DataSourceAutoConfiguration.class. In some runs the audit logger is created and in others it is not. Explain why, and give the fix.
Show answer
@ConditionalOnBean only sees bean definitions registered when your class is evaluated. If DataSourceAutoConfiguration is processed first, the condition matches. If it is processed later, the condition fails. Declare the dependency with @AutoConfiguration(after = DataSourceAutoConfiguration.class) so the order is fixed.
Exercise
Write the test method that checks the property greeting.message=Welcome is used by the auto-configured bean. Use the contextRunner field from the chapter.
Show answer
@Test void usesConfiguredMessage() { this.contextRunner.withPropertyValues("greeting.message=Welcome") .run(context -> assertThat(context.getBean(GreetingService.class).greet("Ana")) .isEqualTo("Welcome, Ana!")); }