Sub topic 2
Conditional Annotations That Drive Spring Boot Decisions
This chapter assumes you know Spring beans, dependency injection, @Configuration and @Bean, and basic Maven or Gradle dependency management.
Conditional annotations that drive the decisions
Spring Boot auto-configuration creates beans only when its conditions match. A condition is an annotation that checks the application before a bean is created.
Common conditions include:
@ConditionalOnClassmatches when a class is available on the classpath.@ConditionalOnMissingBeanmatches when the application has not already defined a matching bean.@ConditionalOnPropertymatches when a named configuration property has a required value.@ConditionalOnBeanmatches when another bean already exists.
For example, an auto-configuration can create a service only when its library is present and the application has not supplied its own service:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
GreetingService greetingService() {
return new GreetingService();
}
}The conditions let Boot provide useful defaults without forcing every application to use them.
Tuning defaults with properties and `@ConfigurationProperties`
Externalized configuration keeps settings out of Java code. @ConfigurationProperties binds a group of properties to a Java object:
@ConfigurationProperties(prefix = "greeting")
public class GreetingProperties {
private String message = "Hello";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}An application can change the default in application.properties:
greeting.message=WelcomeThe auto-configuration enables these properties and injects them into its bean factory method. Use @ConditionalOnProperty when a feature should be optional:
@ConditionalOnProperty(
prefix = "greeting",
name = "enabled",
havingValue = "true",
matchIfMissing = true
)Overriding, backing off, and excluding auto-configuration
A well-designed auto-configuration backs off when the application defines the same bean. @ConditionalOnMissingBean provides this behavior, allowing an application-specific bean to override Boot's default.
You can also exclude an auto-configuration without changing application code:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationUse an exclusion when the configuration is unwanted. Define your own bean when you want to replace or customize its behavior.
Exercise
What happens when an application defines a GreetingService while the auto-configuration uses @ConditionalOnMissingBean?
Show answer
The auto-configuration backs off, so Spring uses the application's GreetingService instead of creating the default one.