Sub topic 6
Switching behavior with properties and the environment
This chapter assumes you know Spring dependency injection, @Configuration and @Bean classes, and application.properties. It also assumes you have seen @ConditionalOnClass and @ConditionalOnMissingBean in earlier chapters. Here you will learn how an auto-configuration reads the environment to decide whether to apply.
Why use the environment
Classpath and bean conditions answer the question "what is present?". Often you also need to ask "what did the user choose?". Spring Boot lets the user answer through properties, files, or the type of application. The conditions in this chapter read that information from the Spring Environment.
| Condition | Matches when |
|---|---|
| `@ConditionalOnProperty` | A property exists, or has a given value |
| `@ConditionalOnResource` | A resource, such as a file on the classpath, exists |
| `@ConditionalOnWebApplication` | The application is a web application (servlet or reactive) |
| `@ConditionalOnNotWebApplication` | The application is not a web application |
| `@ConditionalOnExpression` | A SpEL expression evaluates to true |
@ConditionalOnProperty
@ConditionalOnProperty is the condition you will use most. You name a prefix and a name. Together they form the property key, such as greeting.enabled.
Here is the condition from the greeting example:
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)Three attributes control the result:
havingValueis the value the property must have. If you leave it out, any value exceptfalsematches.matchIfMissingdecides what happens when the property is not set. The default isfalse, so a missing property does not match.namecan list several properties. All of them must match.
The combination above means "apply unless the user sets greeting.enabled=false". This is the standard opt-out switch, and it works because matchIfMissing = true makes the feature on by default.
For a feature that should be opt-in, leave matchIfMissing at its default. The feature then runs only when the user writes greeting.enabled=true.
Other environment conditions
@ConditionalOnResource checks for a file. This suits configuration that depends on a file the user supplies:
@ConditionalOnResource(resources = "classpath:greeting-templates.yaml")@ConditionalOnWebApplication takes an optional type of SERVLET or REACTIVE. Use it so that web-only beans are not created in a batch job or a command-line tool. @ConditionalOnNotWebApplication is the opposite.
@ConditionalOnExpression evaluates a SpEL expression. It is flexible, but the expression is a string that the compiler cannot check, so prefer a dedicated condition when one exists:
@ConditionalOnExpression("${greeting.enabled:true} and ${greeting.loud:false}")Placing the condition
You can put these conditions on a class or on a single @Bean method. A class-level condition switches off every bean in the class. A method-level condition switches off one bean. Mixing both lets you offer one master switch and several smaller ones.
@AutoConfiguration
@ConditionalOnProperty(prefix = "greeting", name = "enabled", matchIfMissing = true)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
@Bean
@ConditionalOnProperty(prefix = "greeting", name = "metrics", havingValue = "true")
public GreetingMetrics greetingMetrics() {
return new GreetingMetrics();
}
}Here greeting.enabled=false removes both beans. greeting.metrics=true adds GreetingMetrics only when the master switch is still on.
Common errors
- Wrong prefix or name. Properties use kebab-case in
@ConditionalOnProperty. Writegreeting.loud-mode, notgreeting.loudMode. Spring's relaxed binding lets users write several forms, but the condition's own key should be canonical. - Value compared as text.
havingValue = "true"compares strings. A user who writesTRUEstill matches, because the comparison ignores case, butyesdoes not match. - Overusing expressions. A typo in a SpEL string fails at runtime, not at compile time.
Exercise
You want a GreetingAuditor bean that is created only when the user explicitly sets greeting.audit=true. Which @ConditionalOnProperty setting gives this behavior, and why?
Show answer
Use @ConditionalOnProperty(prefix = "greeting", name = "audit", havingValue = "true") and leave matchIfMissing at its default of false. When the property is not set, the condition does not match, so the bean is absent. The bean appears only when the user sets greeting.audit=true.
Exercise
A user sets greeting.enabled=false, but a bean marked with only a method-level @ConditionalOnProperty(prefix = "greeting", name = "metrics", havingValue = "true") still appears when greeting.metrics=true. What is missing, and how do you fix it?
Show answer
The master switch sits on neither the class nor this method, so the metrics condition is checked alone. Put @ConditionalOnProperty(prefix = "greeting", name = "enabled", matchIfMissing = true) on the auto-configuration class. Then greeting.enabled=false removes every bean in the class, including the metrics bean.