您的位置:首页 > 房产 > 建筑 > 苏州网上挂号预约平台12320_东莞网站的优化_廊坊网站推广公司_营销计划书7个步骤

苏州网上挂号预约平台12320_东莞网站的优化_廊坊网站推广公司_营销计划书7个步骤

2025/4/7 19:29:23 来源:https://blog.csdn.net/m0_73822222/article/details/146770912  浏览:    关键词:苏州网上挂号预约平台12320_东莞网站的优化_廊坊网站推广公司_营销计划书7个步骤
苏州网上挂号预约平台12320_东莞网站的优化_廊坊网站推广公司_营销计划书7个步骤

SpringBoot条件装配注解

Spring Boot 提供了一系列条件装配注解,用于控制 Bean 的创建和装配过程。以下是一些常用的条件装配注解及其详细介绍:
@ConditionalOnClass
作用:当类路径中存在指定的类时,才会创建该 Bean。
示例:

 @ConditionalOnClass(RedisTemplate.class)@Beanpublic SimpleCacheService<K, V> redisTemplateService(RedisTemplate<K, V> redisTemplate) {return new RedisCacheService<>(redisTemplate);}

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

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

 @ConditionalOnMissingClass("org.springframework.data.redis.core.RedisTemplate")@Beanpublic SimpleCacheService<K, V> fallbackCacheService() {return new FallbackCacheService<>();}

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

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

 @ConditionalOnBean(RedisTemplate.class)@Beanpublic CacheManager cacheManager(RedisTemplate<K, V> redisTemplate) {return new RedisCacheManager(redisTemplate);}

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

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

 @ConditionalOnMissingBean(SimpleCacheService.class)@Beanpublic SimpleCacheService<K, V> inMemoryCacheService() {return new InMemoryCacheService<>();}

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

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

 @ConditionalOnProperty(name = "cache.type", havingValue = "redis")@Beanpublic 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}")@Beanpublic SimpleCacheService<K, V> cacheService() {return new DefaultCacheService<>();}

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

@ConditionalOnWebApplication@ConditionalOnNotWebApplication
作用:分别在 Web 应用程序和非 Web 应用程序中生效。
示例:

 @ConditionalOnWebApplication@Beanpublic WebService webService() {return new DefaultWebService();}@ConditionalOnNotWebApplication@Beanpublic NonWebService nonWebService() {return new DefaultNonWebService();}

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com