阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

使用Conditional

26次阅读
没有评论

共计 1243 个字符,预计需要花费 4 分钟才能阅读完成。

使用 Profile 能根据不同的 Profile 进行条件装配,但是 Profile 控制比较糙,如果想要精细控制,例如,配置本地存储,AWS 存储和阿里云存储,将来很可能会增加 Azure 存储等,用 Profile 就很难实现。

Spring 本身提供了条件装配 @Conditional,但是要自己编写比较复杂的Condition 来做判断,比较麻烦。Spring Boot 则为我们准备好了几个非常有用的条件:

  • @ConditionalOnProperty:如果有指定的配置,条件生效;
  • @ConditionalOnBean:如果有指定的 Bean,条件生效;
  • @ConditionalOnMissingBean:如果没有指定的 Bean,条件生效;
  • @ConditionalOnMissingClass:如果没有指定的 Class,条件生效;
  • @ConditionalOnWebApplication:在 Web 环境中条件生效;
  • @ConditionalOnExpression:根据表达式判断条件是否生效。

我们以最常用的 @ConditionalOnProperty 为例,把上一节的 StorageService 改写如下。首先,定义配置storage.type=xxx,用来判断条件,默认为local

storage:
  type: ${STORAGE_TYPE:local}

设定为 local 时,启用LocalStorageService

@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "local", matchIfMissing = true)
public class LocalStorageService implements StorageService {...}

设定为 aws 时,启用AwsStorageService

@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "aws")
public class AwsStorageService implements StorageService {...}

设定为 aliyun 时,启用AliyunStorageService

@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "aliyun")
public class AliyunStorageService implements StorageService {...}

注意到 LocalStorageService 的注解,当指定配置为local,或者配置不存在,均启用LocalStorageService

可见,Spring Boot 提供的条件装配使得应用程序更加具有灵活性。

练习

使用 Spring Boot 提供的条件装配。

下载练习

小结

Spring Boot 提供了几个非常有用的条件装配注解,可实现灵活的条件装配。

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-08-05发表,共计1243字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中