Sub topic 6
Switching behavior with properties and the environment
This chapter assumes you can write @Configuration and @Bean classes, you know the @ConditionalOnClass and @ConditionalOnMissingBean annotations from the earlier chapters, and you have set values in application.properties. It covers the conditions that read the running environment: @ConditionalOnProperty, @ConditionalOnResource, @ConditionalOnWebApplication and @ConditionalOnExpression.
Why the environment is a condition input
Class and bean conditions answer "what is available?" Property conditions answer "what did the user ask for?" An auto-configuration usually needs both. The class condition says the library is present. The property condition lets the user turn the feature off or select a variant without excluding the whole class.
The Environment is Spring's view of configuration. It merges command-line arguments, system properties, environment variables, application.properties and application.yml. Property conditions read from it, so any source Boot loads before the context is refreshed can drive a condition.
@ConditionalOnProperty
@ConditionalOnProperty has four attributes you will use:
prefix: an optional leading part, such asgreeting. Boot adds the dot for you.name(orvalue): one or more property names, relative to the prefix.havingValue: the value the property must have.matchIfMissing: whether the condition matches when the property is not set at all.
Here is an auto-configuration that uses all four. It matches the one from the Topic Spine, plus a second bean with its own switch.
package com.example.greeting;
import org.springframework.boot.autoconfigure.AutoConfiguration;
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
@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());
}
@Bean
@ConditionalOnProperty(prefix = "greeting", name = "shout", havingValue = "true")
public ShoutMarker shoutMarker() {
return new ShoutMarker();
}
}The class-level condition gates the whole auto-configuration. The method-level condition on shoutMarker gates one bean. Both can sit on the same class, and both must match for the shoutMarker bean to exist.
How the value is compared
The rules are easy to get wrong, so check them against this table. Each row is a different annotation setting on the property greeting.enabled, and each column is a different value in the environment.
| Annotation setting | Property absent | `true` | `false` | `yes` |
|---|---|---|---|---|
| no `havingValue`, `matchIfMissing=false` | no match | match | no match | match |
| `havingValue="true"`, `matchIfMissing=false` | no match | match | no match | no match |
| `havingValue="true"`, `matchIfMissing=true` | match | match | no match | no match |
When you leave havingValue empty, any value matches except false, compared without regard to case. That is why yes matches in the first row. When you set havingValue, the property must equal it, ignoring case.
matchIfMissing=true makes a feature opt-out: it is on unless the user sets the property to false. The default of false makes it opt-in. Choose deliberately. Most Boot starters turn features on by default and let users disable them, which is the opt-out pattern.
Several names at once
When you list several names, every property must match:
@ConditionalOnProperty(prefix = "greeting", name = {"enabled", "shout"}, havingValue = "true")With a single havingValue, all listed properties must have that same value. If you need different values for different properties, use separate annotations on separate beans or classes. @ConditionalOnProperty is not repeatable on one element.
Naming and relaxed binding
Write the names in lowercase kebab-case, such as greeting.max-length. The environment then resolves the other spellings users may supply. An environment variable GREETING_MAX_LENGTH and a property greeting.maxLength both reach the condition, because Boot's property sources apply relaxed matching.
GREETING_ENABLED=false java -jar app.jarjava -jar app.jar --greeting.shout=trueBoth commands change what the conditions see, with no code change.
@ConditionalOnResource
@ConditionalOnResource matches when a resource exists. It takes Spring resource locations:
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
@ConditionalOnResource(resources = "classpath:greeting-templates.txt")Use it when a feature needs a file, such as a template or a licence file. The user enables the feature by supplying the file. If you list several resources, all must exist. Prefer a property for plain on/off switches, because a missing file is harder for users to discover than a documented property.
@ConditionalOnWebApplication
This condition matches on the kind of application the context belongs to.
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
@ConditionalOnWebApplication(type = Type.SERVLET)The type is SERVLET, REACTIVE or ANY. Its counterpart @ConditionalOnNotWebApplication matches in command-line and batch applications. A common use is registering a servlet filter only when a servlet web application is running. Combine it with @ConditionalOnClass when the filter classes may be absent, because the class check protects you from loading types that do not exist.
@ConditionalOnExpression
@ConditionalOnExpression evaluates a Spring Expression Language (SpEL) string. Property placeholders in it are resolved first:
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
@ConditionalOnExpression("${greeting.enabled:true} and ${greeting.shout:false}")The :true and :false are defaults. After substitution, SpEL sees true and false. Without a default, an unset property leaves the placeholder unresolved and context startup fails.
Use expressions only when you need to combine several properties with logic that @ConditionalOnProperty cannot express. They are not type-checked, they give poor error messages, and a typo in the string is found only at startup.
Boot also offers @ConditionalOnJava for Java versions and @ConditionalOnCloudPlatform for platforms such as Kubernetes. They follow the same pattern.
Choosing between the conditions
| Question you need answered | Condition |
|---|---|
| Did the user switch the feature on or off? | `@ConditionalOnProperty` |
| Is a required file present? | `@ConditionalOnResource` |
| Is this a servlet, reactive or non-web application? | `@ConditionalOnWebApplication` or `@ConditionalOnNotWebApplication` |
| Do several properties combine in a custom rule? | `@ConditionalOnExpression` |
Gotchas
- Properties must exist early. Conditions on auto-configurations are evaluated while the context loads its configuration classes. Values from
application.properties, environment variables and command-line arguments are available by then. A@PropertySourceannotation on a user configuration class is registered while that class is being parsed. Do not count on it to drive conditions in other classes. - Beans cannot feed property conditions. A property condition reads the
Environment, not bean state. A value computed by a bean at runtime is invisible to it. - Profiles are separate.
@Profileis also a condition, but auto-configurations normally use properties. A property is more specific, works with any source, and does not tie a library to the user's profile names. - Typos fail silently. A misspelled property name makes the condition see "missing". The result follows
matchIfMissing, with no error. The--debugreport shows which property a condition looked for. - Class-level and method-level conditions combine with AND. If the class condition fails, no method condition is checked.
Testing the switch
ApplicationContextRunner lets you set properties per test. This test checks that greeting.shout controls the ShoutMarker bean.
package com.example.greeting;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class ShoutSwitchTests {
record Marker(String name) {
}
@Configuration(proxyBeanMethods = false)
static class SwitchConfig {
@Bean
@ConditionalOnProperty(prefix = "greeting", name = "shout", havingValue = "true")
Marker marker() {
return new Marker("shout");
}
}
private final ApplicationContextRunner runner = new ApplicationContextRunner()
.withUserConfiguration(SwitchConfig.class);
@Test
void absentWhenPropertyIsMissing() {
this.runner.run(context -> assertThat(context).doesNotHaveBean(Marker.class));
}
@Test
void presentWhenPropertyIsTrue() {
this.runner.withPropertyValues("greeting.shout=true")
.run(context -> assertThat(context).hasSingleBean(Marker.class));
}
@Test
void absentWhenPropertyIsFalse() {
this.runner.withPropertyValues("greeting.shout=false")
.run(context -> assertThat(context).doesNotHaveBean(Marker.class));
}
}The first test covers the "missing" row of the table. Always test the missing case, because it is the one users hit by default.
Exercise
A feature uses @ConditionalOnProperty(prefix = "cache", name = "mode") with no havingValue and the default matchIfMissing. What happens when the user sets cache.mode=false, cache.mode=off, or sets nothing?
Show answer
With cache.mode=false the condition does not match, because an empty havingValue matches any value except false. With cache.mode=off it matches, because off is not false. With nothing set it does not match, because matchIfMissing defaults to false.
Exercise
You want a bean that exists only in a servlet web application and only when audit.enabled is true, and it should be on by default. Which conditions do you put on the bean method?
Show answer
Use @ConditionalOnWebApplication(type = Type.SERVLET) and @ConditionalOnProperty(prefix = "audit", name = "enabled", havingValue = "true", matchIfMissing = true). Both must match, so the bean exists in servlet applications unless the user sets audit.enabled=false.