introduction
Spring Boot'sConditional Annotations
It is one of the core mechanisms of automatic configuration (Auto-Configuration). They allow developers to follow specific conditionsDynamically determine whether to load a bean or configuration class
, thus achieving flexible"Configuration on demand"
. This article will systematically sort out all commonly used conditional annotations and combine code examples to illustrate their functions and usage scenarios.
1. The core mechanism of conditional annotation
Meta annotation: @Conditional
As the basis for all conditional annotations,@Conditional
By implementingCondition
Interfacematches()
Method to make conditional judgment. If the conditions are met, the Bean or configuration class will take effect; otherwise, it will be skipped.
Example: Custom condition class checks whether JdbcTemplate exists
public class JdbcTemplateCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return ("", ()); } }
2. Detailed explanation of the built-in condition annotations of SpringBoot
SpringBoot is based on@Conditional
The following commonly used annotations are extended to cover most automated configuration scenarios.
1. @ConditionalOnClass and @ConditionalOnMissingClass
-
effect
: According to the classpathWhether the specified class exists
To decide whether it takes effect -
Typical scenarios
: Check whether the dependency library exists in the automatic configuration class - Example: When introducing a project
Hibernate
Automatically configure JPA-related beans
@Configuration @ConditionalOnClass({ , }) public class JpaAutoConfiguration { // Take effect when the classpath has DataSource and EntityManager}
2. @ConditionalOnBean and @ConditionalOnMissingBean
-
effect
: According to the containerWhether a specified bean exists
To decide whether it takes effect -
Typical scenarios
: Avoid repeated registration of beans, or provide custom override for default beans - Example: When the user is not customized
DataSource
When registering the default data source
@Bean @ConditionalOnMissingBean() public DataSource defaultDataSource() { return new HikariDataSource(); }
3、@ConditionalOnProperty
-
effect
: According to the configuration file (e.g.) determines whether the property value in ) determines whether it takes effect
-
Typical scenarios
: Function switch, multi-environment configuration switching - Example: Enable cache function according to configuration
@Configuration @ConditionalOnProperty(name = "", havingValue = "true") public class CacheConfig { // Load when =true}
4. @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
-
effect
: Decide whether it takes effect based on whether the current application is a web application -
Typical scenarios
: Distinguish between web environment and non-web environment (such as batch tasks) - Example: Register MVC components only in web applications
@Configuration @ConditionalOnWebApplication public class WebMvcConfig { // Only effective in the web environment}
5、@ConditionalOnExpression
-
effect
: Combining complex conditions through SpEL expressions -
Typical scenarios
: Multiple conditions or complex logical judgments are required at the same time - Example: Take effect when both the property switch and the classpath exist
@Bean @ConditionalOnExpression( "${} && T().isAvailable()" ) public FeatureBean featureBean() { return new FeatureBean(); }
6、@ConditionalOnResource
-
effect
: Check whether the specified resource file exists -
Typical scenarios
: Load configuration according to the existence of configuration files or key files - Example: Exist
Override the default configuration
@Configuration @ConditionalOnResource(resources = "classpath:") public class OverrideConfig { // Take effect when the file exists in the classpath}
7、@ConditionalOnJava
-
effect
: Decide whether it takes effect based on the current JVM version -
Typical scenarios
: Compatible with different Java versions - Example: Enable modular configuration only if JVM version is 11 or higher
@Configuration @ConditionalOnJava(range = .EQUAL_OR_NEWER, value = ) public class Java11Config { // Effective under Java 11+}
8、@ConditionalOnSingleCandidate
-
effect
: Effective when there is a bean of the specified type in the container and there is only one bean of the specified type -
Typical scenarios
: Automatically configure scenarios that rely on a specific single bean - Example: When there is only one
DataSource
Automatically configure transaction manager
@Bean @ConditionalOnSingleCandidate() public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); }
3. Combination usage conditions annotation
Multiple conditional annotations can be used in combination to achieve more refined control
@Configuration @ConditionalOnClass({}) @ConditionalOnProperty(name = "", matchIfMissing = true) public class RedisAutoConfig { // Take effect when RedisClient exists and configuration is enabled (or not configured).}
4. The underlying principle of conditional annotation
When Spring Boot is started,Conditional annotation parser
(likeConditionEvaluator
) Scan all configuration classes and implement conditional assembly in combination with the following steps
-
Condition collection
: Analyze the conditional annotations on the configuration class and generate the correspondingCondition
Example -
Conditional matching
: Calledmatches()
Method, judge the classpath, Bean container status, environment variables, etc. -
Dynamic registration
: Only beans that meet the conditions are registered, unmet configuration classes will be skipped
Summarize
Spring Boot's conditional annotations provide developers with powerfulDynamic configuration capability
, understanding its principles and applicable scenarios is the key to building flexible and scalable applications. By reasonably combining these annotations, "intelligent" automatic configuration logic can be achieved while avoiding redundant code. In actual development, it is recommended to combine Spring Boot's automatic configuration source code (such asspring-boot-autoconfigure
Module) In-depth learning.
This article about the full analysis of SpringBoot conditional annotations: Detailed explanation of core functions and usage scenarios. For more related SpringBoot conditional annotations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!