Spring auto configuration - Conditional
Table of Contents
Use cases:
- When we want to load certain beans based on a condition.
- We have an interface and there are two (or more) classes implementing that interface. Based on a property (externally configured), we want to use one or the other types of implementations.
- e.g. If we are switching from Elasticsearch to Opensearch, and we want only one type of configuration to load based on a toggle setting coming from spring-cloud-config server.
- Using this, we can control which beans are loaded at application start-up.
When building a Spring Boot app, we sometimes want to only load beans or modules into the application context if some condition is met.
Spring has introduced the @Conditional annotation that allows us to define custom conditions to apply to parts of our application context. Spring Boot builds on top of that and provides some pre-defined conditions so we don’t have to implement them ourselves.
@Configuration
@ConditionalOnProperty(
value="module.enabled",
havingValue = "true",
matchIfMissing = true)
class CrossCuttingConcernModule {
...
}