Skip to main content
Configuration, profiles, conditions · Topic 4 of 5

Conditional beans

Definition​

A conditional bean is created only when a condition is true, for example a property has a value, a class is on the classpath, or no other bean of that type exists. Spring Boot uses these conditions to decide what to auto-configure.

Example code​

A feature that is switched on by a property

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import java.util.Map;

class FastSearch { }
class Cache { }

@Configuration
class FeatureConfig {
@Bean
@ConditionalOnProperty(name = "feature.fast-search", havingValue = "true") // only when the property is "true"
FastSearch fastSearch() { return new FastSearch(); }

@Bean
@ConditionalOnMissingBean // only if nobody defined a Cache
Cache defaultCache() { return new Cache(); }
}

class Demo {
static void run(String value) {
var context = new AnnotationConfigApplicationContext();
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of("feature.fast-search", value)));
context.register(FeatureConfig.class);
context.refresh();
System.out.println("feature.fast-search=" + value + " -> FastSearch bean exists: " + (context.getBeansOfType(FastSearch.class).size() == 1));
context.close();
}

public static void main(String[] args) {
run("true");
run("false");
}
}

// Output:
// feature.fast-search=true -> FastSearch bean exists: true
// feature.fast-search=false -> FastSearch bean exists: false

Finished this page? Track your progress (saved only in your browser).