1. Brief description
In Spring Boot, the @Conditional annotation is used to implement conditional bean assembly, that is, to decide whether to load a bean based on specific conditions. It is an extension mechanism in the Spring framework and is often used to implement modular, configurable component loading.
This article will introduce in detail the annotations related to @Conditional, including @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, etc., and explain how to use them in combination with practical application examples.
2. @Conditional annotation overview
@Conditional is a conditional assembly annotation introduced by Spring 4. It can decide whether to create a bean based on the external environment or configuration status.
Its core interface is:
public interface Condition { boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); }
Any class that implements the Condition interface can be used for custom condition judgment.
@Configuration public class MyConfig { @Bean @Conditional() public MyService myService() { return new MyService(); } }
Among them, the Condition interface needs to be implemented and judgment logic is provided.
3. Spring Boot built-in @Conditional related annotations
Spring Boot provides some common @Conditional annotations, simplifying the logic of conditional judgment:
annotation | effect |
---|---|
@ConditionalOnClass |
The bean is loaded only when a class exists in the classpath |
@ConditionalOnMissingClass |
Under the classpathDoes not existThe bean is loaded only when a class is |
@ConditionalOnBean |
The current bean is loaded only when the specified bean exists in the container |
@ConditionalOnMissingBean |
When in the containerDoes not existThe current bean is loaded only when a bean is specified |
@ConditionalOnProperty |
The current bean is loaded when the specified configuration property meets the condition |
@ConditionalOnExpression |
When the specified SpEL expression istrue When the current bean is loaded |
@ConditionalOnJava |
The current bean is loaded when the Java version meets the requirements |
@ConditionalOnWebApplication |
The current bean is loaded when the application is a web application |
@ConditionalOnNotWebApplication |
When applyingnoThe current bean is loaded only when the web application is applied. |
3.1 @ConditionalOnClass usage example (classpath detection)
We hope that in the Spring Boot project, the MyService bean will be registered only when this class exists under the classpath.
import ; import ; import ; @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnClass(name = "") public MyService myService() { return new MyService(); } }
explain:
- If present, the MyService is created.
- If it does not exist, the MyService will not be loaded.
3.2 @ConditionalOnMissingBean (loaded when Bean is missing)
If the user does not manually define MyService, a default implementation is provided.
import ; import ; import ; @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { return new MyService("Default Implementation"); } }
explain:
- If MyService already exists in the Spring container, no new bean is created.
- The default implementation will be registered only if MyService does not exist.
3.3 @ConditionalOnProperty (Loading Bean based on configuration item conditions)
We want MyService to be created only when =true.
import ; import ; import ; @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnProperty(name = "", havingValue = "true", matchIfMissing = false) public MyService myService() { return new MyService(); } }
explain:
- If =true is included, MyService will be created.
- If =false, or the property is not defined, MyService will not be loaded.
Enable in:
=true
3.4 @ConditionalOnBean (loaded only when a specific bean exists)
OrderService is created when the UserService exists.
import ; import ; import ; @Configuration public class OrderServiceConfiguration { @Bean @ConditionalOnBean() public OrderService orderService() { return new OrderService(); } }
explain:
- If the UserService exists, the OrderService is also created.
- If the UserService does not exist, the OrderService will not be loaded.
3.5 @ConditionalOnExpression (loaded based on SpEL expression)
AdvancedService is created when it is greater than 8080.
import ; import ; import ; @Configuration public class AdvancedConfig { @Bean @ConditionalOnExpression("#{T().parseInt('${:8080}') > 8080}") public AdvancedService advancedService() { return new AdvancedService(); } }
explain:
> 8080, AdvancedService will be loaded.
In other cases, the bean is not created.
Configure in:
=9090
3.6 Combined with @ConditionalOnClass to implement hot plug-in of Starter components
We want to create a Spring Boot Starter component. If a RedisTemplate exists under the user's classpath, the Redis-related beans will be loaded automatically.
step:
Create Starter Components
@Configuration @ConditionalOnClass() public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); (factory); return template; } }
Use Starter
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
If Redis dependencies are introduced, RedisAutoConfiguration will take effect automatically.
If the Redis dependency is not introduced, the RedisTemplate will not be created.
4. Summary
- @Conditional and its derivative annotations give Spring Boot the ability to configure and hot plug.
- @ConditionalOnClass can be used to determine whether a class exists and is often used for automatic assembly of Starter components.
- @ConditionalOnProperty is suitable for configuration-based conditional loading for enhanced flexibility.
- @ConditionalOnBean and @ConditionalOnMissingBean are suitable for component dependency management.
Using these annotations reasonably can build more modular, flexible, and configurable Spring Boot applications.
The above is the introduction and practice of @Conditional annotation in SpringBoot. For more information about SpringBoot @Conditional annotation, please follow my other related articles!