Learnitweb

@ConditionalOnProperty annotation in Spring Boot

1. Introduction to @ConditionalOnProperty

In Spring Boot, the @ConditionalOnProperty annotation is used to conditionally enable or disable a bean registration based on the presence and value of a property in the application’s configuration files (like application.properties or application.yml).

It is part of the Spring Boot auto-configuration mechanism and is mainly used to write conditional logic in configuration classes.

2. Use Case

You can use @ConditionalOnProperty when:

  • You want to load a bean only if a specific property is set.
  • You want to provide optional or toggleable features in your application.
  • You are writing a custom auto-configuration class.
  • You want to enable/disable components like metrics, schedulers, or data sources based on a config flag.

3. Basic Syntax

@ConditionalOnProperty(
    name = "feature.enabled",
    havingValue = "true",
    matchIfMissing = false
)

This means:

  • The bean will be registered only if the property feature.enabled is present and set to true.
  • If the property is missing and matchIfMissing = false, the bean will not be loaded.

4. Parameters Explained

ParameterTypeDescription
nameString[]The name(s) of the property to check.
prefixStringA prefix to apply to each property name. Useful when grouping properties.
havingValueStringThe value that the property must have for the condition to match.
matchIfMissingbooleanWhether the condition should match if the property is missing. Default is false.