1. Preface
In Spring Boot,Conditional annotationis a powerful feature that allows us to dynamically register or skip specific beans based on certain conditions. in,@ConditionalOnBean
It is one of the most commonly used conditional annotations, and its function is:The current bean is registered only when the specified bean exists in the Spring container.。
This article will introduce in detail@ConditionalOnBean
Use scenarios, principles, and provide multiple examples to help understand.
2. @ConditionalOnBean Functions and Basic Usage
2.1 The role of @ConditionalOnBean
@ConditionalOnBean
Mainly used in the following scenarios:
- Loading beans on demand: Only when a bean exists, another bean is created.
- Modular design: Some functional modules need to rely on specific beans to enable, for exampleAutomatic configuration will only take effect if a component exists。
-
Avoid Bean Conflicts: If a bean depends on other beans, it can be used
@ConditionalOnBean
Make sure it does not fail to load due to lack of dependencies.
2.2 Basic usage
Example: WhenDataSource
Created when a bean existsMyService
Bean
import ; import ; import ; import ; @Configuration public class MyConfig { @Bean public DataSource dataSource() { // Simulate DataSource instance here, and HikariDataSource, Druid, etc. are actually available return new FakeDataSource(); } @Bean @ConditionalOnBean() // Create MyService only if DataSource exists public MyService myService() { return new MyService(); } } class MyService { public MyService() { ("MyService was created"); } } class FakeDataSource implements DataSource { // Here you can simulate the DataSource method}
Execution results:
MyService was created
ifdataSource()
The method is commented out, thenMyService
Will not be created.
3. @ConditionalOnBean Details
@ConditionalOnBean
Provides multiple attributes to enable more flexible control of the creation of beans.
3.1 value and type attributes (specify the Bean type)
Used to specify that a certain type of bean exists, the current bean will be registered.
@Bean @ConditionalOnBean(value = ) // Take effect only if DataSource existspublic MyRepository myRepository() { return new MyRepository(); }
Equivalent to:
@Bean @ConditionalOnBean(type = "") // Use fully qualified class namespublic MyRepository myRepository() { return new MyRepository(); }
the difference:
-
value
: Use the Class type directly, and it is safer to check when compiling. -
type
: Use strings, which can be used to avoid some classes being not found (such as optional dependencies).
3.2 name attribute (specify the bean name)
ForSpecify whether a bean name existsto determine whether the current bean is loaded.
@Bean @ConditionalOnBean(name = "customBean") // Register only if a bean named customBean existspublic MyComponent myComponent() { return new MyComponent(); }
3.3 annotation attribute (specify the annotation that the bean needs to be annotated)
You can specify whether certain beans contain specific annotations, and if so, the current bean will be registered.
@Bean @ConditionalOnBean(annotation = ) // Effective only if a bean with @Repository annotation existspublic MyService myService() { return new MyService(); }
3.4 search attributes (search scope)
By default,@ConditionalOnBean
Will only be inCurrent application contextFind beans, not searchFather context(i.e. Spring Boot'sApplicationContext
level).
search
Options can specify the search range:
-
ALL
: in all fathers and sonsApplicationContext
Search in. -
CURRENT
(Default): Search only for the currentApplicationContext
。
@Bean @ConditionalOnBean(value = , search = ) // Search in all contextspublic MyService myService() { return new MyService(); }
4.@ConditionalOnBean usage scenario
Scenario 1: Loading database-related beans on demand
If in the applicationUsed the database, then provide aDatabaseService
, otherwise it will not be created:
@Bean @ConditionalOnBean() public DatabaseService databaseService() { return new DatabaseService(); }
Scenario 2: Enable some automatic configurations
Spring Boot'sspring-boot-autoconfigure
Massive use of modules@ConditionalOnBean
to control automatic configuration. For example:
Only whenDispatcherServlet
When it exists,Spring MVC-related automatic configuration will only take effect。
@Configuration @ConditionalOnBean() public class MvcAutoConfiguration { // Spring MVC configuration takes effect only if the DispatcherServlet exists}
Scenario 3: Optional dependency components
Sometimes, certain features are optional, such as creating a cache manager when a Redis component exists:
@Bean @ConditionalOnBean(name = "redisTemplate") // Load only when redisTemplate existspublic CacheManager cacheManager() { return new RedisCacheManager(); }
5. @ConditionalOnBean vs @ConditionalOnMissingBean
annotation | effect |
---|---|
@ConditionalOnBean |
When the specified bean exists, just register the current bean |
@ConditionalOnMissingBean |
When the specified bean does not exist, just register the current bean |
Example:
@Bean @ConditionalOnMissingBean() // Create only if DataSource does not existpublic DataSource defaultDataSource() { return new DefaultDataSource(); }
6. Conclusion
In Spring Boot,@ConditionalOnBean
Can help us accordingIs there a specific beanComeDynamic registration Bean, widely usedLoading on demand, automatic configurationetc.
Summarize:
✅ Specify the bean type:@ConditionalOnBean()
✅ Specify the Bean name:@ConditionalOnBean(name = "customBean")
✅ Specify Bean Annotation:@ConditionalOnBean(annotation = )
✅ Search range:@ConditionalOnBean(search = )
You've used it in the project@ConditionalOnBean
Is it? Welcome to leave a message to share your experience! 🚀
This is the end of this article about the detailed explanation of @ConditionalOnBean annotation in Spring Boot. For more related Spring Boot @ConditionalOnBean annotation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!