SpringBoot条件装配注解

SpringBoot条件装配注解

Spring Boot 提供了一系列条件装配注解,用于控制 Bean 的创建和装配过程。以下是一些常用的条件装配注解及其详细介绍:
@ConditionalOnClass

作用:当类路径中存在指定的类时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnClass(RedisTemplate.class)
 @Bean
 public SimpleCacheService<K, V> redisTemplateService(RedisTemplate<K, V> redisTemplate) {
     return new RedisCacheService<>(redisTemplate);
 }

说明:只有当类路径中存在 RedisTemplate 类时,才会创建 redisTemplateService Bean。

@ConditionalOnMissingClass

作用:当类路径中不存在指定的类时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnMissingClass("org.springframework.data.redis.core.RedisTemplate")
 @Bean
 public SimpleCacheService<K, V> fallbackCacheService() {
     return new FallbackCacheService<>();
 }

说明:只有当类路径中不存在 RedisTemplate 类时,才会创建 fallbackCacheService Bean。

@ConditionalOnBean

作用:当容器中存在指定类型的 Bean 时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnBean(RedisTemplate.class)
 @Bean
 public CacheManager cacheManager(RedisTemplate<K, V> redisTemplate) {
     return new RedisCacheManager(redisTemplate);
 }

说明:只有当容器中存在 RedisTemplate Bean 时,才会创建 cacheManager Bean。

@ConditionalOnMissingBean

作用:当容器中不存在指定类型的 Bean 时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnMissingBean(SimpleCacheService.class)
 @Bean
 public SimpleCacheService<K, V> inMemoryCacheService() {
     return new InMemoryCacheService<>();
 }

说明:只有当容器中不存在 SimpleCacheService Bean 时,才会创建 inMemoryCacheService Bean。

@ConditionalOnProperty

作用:当配置文件中的某个属性满足特定条件时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnProperty(name = "cache.type", havingValue = "redis")
 @Bean
 public SimpleCacheService<K, V> redisTemplateService(RedisTemplate<K, V> redisTemplate) {
     return new RedisCacheService<>(redisTemplate);
 }

说明:只有当配置文件中 cache.type 属性的值为 redis 时,才会创建 redisTemplateService Bean。

@ConditionalOnExpression

作用:当 SpEL 表达式的结果为 true 时,才会创建该 Bean。

示例:

复制代码
 @ConditionalOnExpression("${cache.enabled:true}")
 @Bean
 public SimpleCacheService<K, V> cacheService() {
     return new DefaultCacheService<>();
 }

说明:只有当配置文件中的 cache.enabled 属性为 true 或未设置时,才会创建 cacheService Bean。

@ConditionalOnWebApplication@ConditionalOnNotWebApplication

作用:分别在 Web 应用程序和非 Web 应用程序中生效。

示例:

复制代码
 @ConditionalOnWebApplication
 @Bean
 public WebService webService() {
     return new DefaultWebService();
 }
 
 @ConditionalOnNotWebApplication
 @Bean
 public NonWebService nonWebService() {
     return new DefaultNonWebService();
 }

这些注解可以帮助开发者根据不同的运行环境和配置条件来动态装配 Bean,提高应用的灵活性和可扩展性。

相关推荐
鲁Q同志22 分钟前
若依导出模板时设置动态excel下拉框(表连接的)
java·excel
2025学习35 分钟前
Spring循环依赖导致Bean无法正确初始化
后端
l0sgAi43 分钟前
最新SpringAI 1.0.0正式版-实现流式对话应用
后端
parade岁月1 小时前
从浏览器存储到web项目中鉴权的简单分析
前端·后端
汇匠源1 小时前
Java 零工市场小程序 | 灵活就业平台 | 智能匹配 | 日结薪系统 | 用工一站式解决方案
java·小程序
why1511 小时前
java IO流
java
用户91453633083911 小时前
ThreadLocal详解:线程私有变量的正确使用姿势
后端
Asurplus1 小时前
【微信小程序】4、SpringBoot整合WxJava生成小程序码
spring boot·微信小程序·wxjava·小程序码
二宝哥2 小时前
maven命令安装jar包到本地仓库
java·maven·jar