SoFunction
Updated on 2025-04-06

Complete analysis of Spring Boot conditional annotation @ConditionalOnProperty

Preface

In Spring Boot projects, sometimes we want to decide whether to enable a feature or load a component based on a property value in the configuration file. at this time,@ConditionalOnPropertyAnnotations can work. It controls the loading of beans or configuration classes through the attribute values ​​of the configuration file, making our program more flexible.

This article will introduce in detail@ConditionalOnPropertyThe usage of   and passFunctional switchandEnvironment configurationTwo practical scenarios to show its power.

1. @ConditionalOnProperty Basic usage

grammar

@ConditionalOnProperty(
    prefix = "Prefix",
    name = "Attribute Name",
    havingValue = "Specify Value",
    matchIfMissing = false
)

Parameter description:

  • prefix: The prefix part of the property.
  • name: Attribute name.
  • havingValue: The value of the attribute andhavingValueWhen equality is true (not specified by default).
  • matchIfMissing: Whether to load the configuration if the attribute is not defined (defaultfalse, i.e. it is not loaded when undefined).

2. Practical scenes

Scene 1: Function switch

In actual projects, we may need to control the enablement or disabling of a certain feature through a property in the configuration file. For example, whether to enable a timed task, whether to enable a certain service, etc.

Example: Enable log enhancement via function switch

Step 1: Configuration file definition switch

existAdd a switch attribute to the file:

=true

Step 2: Implement log enhancement function

use@ConditionalOnPropertyTo determine whether to load log enhancement beans:

import ;
import ;
import ;

@Configuration
@ConditionalOnProperty(prefix = "-enhancement", name = "enabled", havingValue = "true", matchIfMissing = false)
public class LoggingEnhancementConfig {

    @Bean
    public String loggingEnhancement() {
        ("Log Enhancement is enabled!");
        return "Logging Enhancement Activated";
    }
}

Step 3: Test

  • when=truehour,LoggingEnhancementConfigThe class will be loaded and the console will output:
    Log enhancement enabled!
    
  • when=falseor when not configured,LoggingEnhancementConfigThe class will not be loaded.

Scenario 2: Environment configuration

In different environments (development, testing, production), we may need to load different configurations. For example, in-memory databases are used in the development environment and in the production environment, MySQL databases are used.

Example: Selecting data source in different environments

Step 1: Configuration File

existConfigure the environment identifier:

# Development Environment=dev

# Production environment# =prod

Step 2: Development environment data source configuration

import ;
import ;
import ;

import ;
import ;

@Configuration
@ConditionalOnProperty(prefix = "", name = "env", havingValue = "dev")
public class DevDataSourceConfig {

    @Bean
    public DataSource devDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        ("org.");
        ("jdbc:h2:mem:testdb");
        ("sa");
        ("");
        ("Development Environment: Loading Memory Database");
        return dataSource;
    }
}

Step 3: Production environment data source configuration

import ;
import ;
import ;

import ;
import ;

@Configuration
@ConditionalOnProperty(prefix = "", name = "env", havingValue = "prod")
public class ProdDataSourceConfig {

    @Bean
    public DataSource prodDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        ("");
        ("jdbc:mysql://localhost:3306/proddb");
        ("root");
        ("password");
        ("Production Environment: Loading MySQL Database");
        return dataSource;
    }
}

Step 4: Test

  • Development Environment=devConsole output:

    Development Environment:Loading the in-memory database
    
  • Production environment=prodConsole output:

    Production environment:load MySQL database
    

3. Summary of common application scenarios

  • Functional switch: Dynamically enable or disable a functional module (such as timing tasks, monitoring services, etc.).
  • Environment configuration: Load different configurations (such as data source, log level, etc.) according to different environments.
  • Component selection: Load specific third-party components (such as different cache implementations Redis/ehcache) according to the configuration.
  • Service switching: Implement automatic switching of backup services or downgraded services.

4. Summary

@ConditionalOnPropertyIt is a very practical conditional annotation in Spring Boot. You can flexibly control the loading of beans and configuration classes through configuration files, avoid unnecessary waste of resources, and improve the maintainability of the system.

Through examples of functional switches and environment configuration, we can see@ConditionalOnPropertyHow to make the code clearer and the configuration more flexible greatly meet the needs of developers in different scenarios.

Best Practices

  • Use unified prefix management properties in configuration files to avoid conflicts.
  • The naming of switch attributes should be clear and intuitive, such as
  • For important functional switches, you can combine the document to clarify their functions and default values.

I hope this blog can help you better grasp it@ConditionalOnPropertyThe usage of  make your Spring Boot project more flexible and configurable!

Summarize

This is the article about the complete analysis of Spring Boot condition annotations @ConditionalOnProperty. For more relevant Spring Boot condition annotations @ConditionalOnProperty content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!