Spring auto configuration - Conditional

Use cases:

  1. When we want to load certain beans based on a condition.
  2. 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.
    1. 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.
  3. 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 {
  ...
}

Sample implementation

https://github.com/explorer436/programming-playground/tree/main/java-playground/spring-conditional-autoconfiguration

Reading material

  1. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Conditional.html
  2. https://reflectoring.io/spring-boot-conditionals/