Sub topic 11
Writing your own auto-configuration
This chapter assumes you know Spring beans, @Configuration and @Bean, and how to build a Maven or Gradle project. It also assumes you have read the earlier chapters on conditional annotations and @ConfigurationProperties. Here you combine those pieces into a small library that configures itself.
What you are building
An auto-configuration is a regular @Configuration class that Boot loads only when its conditions match. You will build a library with three parts:
- A plain class,
GreetingService, that does the work. - A properties class,
GreetingProperties, that lets users change the message. - An auto-configuration class that creates the service bean unless the user already defined one.
Step 1: The library class
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 + "!";
}
}This class has no Spring annotations. A library should not force Spring on code that does not need it.
Step 2: The properties
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;
}
}The field initializer is the default. A user who sets greeting.message=Welcome in application.properties replaces it without touching code.
Step 3: 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.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@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:
@AutoConfigurationmarks the class as an auto-configuration. It is a specialized@Configuration.@ConditionalOnClassskips the whole class ifGreetingServiceis not on the classpath.@EnableConfigurationPropertiesregistersGreetingPropertiesas a bean and binds thegreeting.*properties to it.@ConditionalOnMissingBeanmakes the bean a default. If the application defines its ownGreetingService, yours backs off.
Step 4: Register it
Boot does not find your class by scanning. You list it in a file at META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in your library's resources:
com.example.greeting.GreetingAutoConfigurationPut one fully qualified class name on each line. A typo here causes no error. The class is simply never loaded.
Step 5: Verify
Add the library to an application and inject the service:
@RestController
class HelloController {
private final GreetingService greetingService;
HelloController(GreetingService greetingService) {
this.greetingService = greetingService;
}
@GetMapping("/hello")
String hello() {
return greetingService.greet("Ann");
}
}With no properties set, /hello returns Hello, Ann!. Set greeting.message=Welcome and it returns Welcome, Ann!.
If the bean is missing, start the application with --debug and look for GreetingAutoConfiguration in the conditions report. It appears under positive matches, negative matches, or not at all. Not at all usually means the imports file is missing or misnamed.
Common mistakes
| Symptom | Likely cause |
|---|---|
| Class never appears in the conditions report | The imports file has the wrong path, name, or class name |
| User's bean and yours both exist | `@ConditionalOnMissingBean` is missing, or the class is component-scanned |
| `greeting.message` has no effect | `@EnableConfigurationProperties` is missing, or the setter is absent |
| `NoClassDefFoundError` at startup | Conditions are on the method instead of the class, for classes that may be absent |
Exercise
Your auto-configuration defines a GreetingService bean with @ConditionalOnMissingBean, but the application also defines its own GreetingService bean. Which bean ends up in the context, and why?
Show answer
Only the application's bean. Boot processes auto-configurations after user configuration, so @ConditionalOnMissingBean finds the user's bean and the auto-configured one backs off.