SoFunction
Updated on 2025-05-11

The difference between using Java annotation @Conditional and @Profile

Preface

In Spring application development, conditional bean registration is a key link in configuration flexibility.@Profileand@ConditionalThey are two common mechanisms provided by Spring. They can dynamically determine whether certain beans are loaded according to different conditions, thereby realizing environmental isolation, module selection, feature switches and other functions. This article will systematically explain the role, usage of these two annotations, the differences and synergy between them.

1. What is @Profile

Basic concepts

@ProfileAnnotations are used to specify that a bean or configuration class is effective only in the specified Profile environment. It is often used to distinguish configurations of development, testing and production environments.

@Configuration
@Profile("dev")
public class DevDataSourceConfig {
    @Bean
    public DataSource dataSource() {
        return new HikariDataSource("jdbc:mysql://localhost/dev_db");
    }
}

Activation method

  • : : dev
  • Startup parameters:--=dev
  • SpringApplicationBuilder: .profiles("dev")

2. What is @Conditional

Basic concepts

@ConditionalAnnotations provide more general conditional judgment capabilities. Its parameters are implementedConditionThe interface class, Spring will call the classmatchesThe method determines whether to load the corresponding bean.

@Bean
@Conditional()
public ListService windowsListService() {
    return new WindowsListService();
}

Custom Condition Example

public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return ().getProperty("").contains("Windows");
    }
}

3. Comparison of the two

Dimension @Profile @Conditional
granularity Environment-level configuration Code level, attribute level, arbitrary conditions
Simplicity Simple and easy to use, agreement is greater than configuration Flexible but requires manual implementationConditioninterface
Applicable scenarios Multi-environment configuration isolation (dev/test/prod) Control bean loading according to any runtime conditions, such as system variables, class existence, etc.
Compositionality Can cooperate@Configuration@Componentuse Can be combined with any Spring annotation
The underlying principle The essence is@Conditional() Completely customizedConditionImplementation Class

4. Practical examples

Profile+Conditional combined use

@Configuration
@Profile("prod")
public class CacheConfig {
    @Bean
    @Conditional()
    public CacheManager redisCacheManager() {
        return new RedisCacheManager();
    }
}

This configuration means that onlyprodIn the environment, and exists in the classpathRedisClientCreated when the class isredisCacheManager Bean。

5. Advanced @Conditional derived annotation

Spring Boot provides multiple@ConditionalThe derived annotation simplifies the conditional configuration of common scenarios:

@ConditionalOnProperty

Function: Decide whether to load a Bean based on whether a property exists and its value in the configuration file

@Bean
@ConditionalOnProperty(name = "", havingValue = "true", matchIfMissing = false)
public UserFeatureService featureService() {
    return new UserFeatureService();
}

@ConditionalOnMissingBean

Function: Register the current bean only when the specified bean does not exist, and is used to provide a default implementation.

@Bean
@ConditionalOnMissingBean()
public DataSource defaultDataSource() {
    return new HikariDataSource();
}

@ConditionalOnBean

Function: When a bean exists in the Spring context, the current bean is injected.

@Bean
@ConditionalOnBean()
public CacheManager redisCacheManager() {
    return new RedisCacheManager();
}

@ConditionalOnClass

Function: Bean is loaded when a certain class exists in the classpath, which is suitable for automatic assembly of components.

@Bean
@ConditionalOnClass(name = "")
public JsonConverter jsonConverter() {
    return new JacksonJsonConverter();
}

These annotations greatly simplify the conditional logic of automatic configuration and are the core support of Spring Boot automatic assembly mechanism.

6. Summary

annotation effect Suitable for scenes
@Profile Activate Bean by environment (such as dev/prod) Multi-environment isolation configuration
@Conditional Activate beans based on any conditions (such as operating system, classpath) Modular configuration with flexible control and scalability

In actual projects, the two can be used in combination to build a highly flexible and configurable application architecture, which is an important tool for Spring framework decoupling and module control.

It is recommended to use it in configuration classes@ProfileDo environmental isolation and use in specific beans@ConditionalDo condition control.

The above is the detailed content of the difference between Java annotation @Conditional and @Profile. For more information about Java annotation @Conditional and @Profile, please follow my other related articles!