Spring开发系列教程(37)——使用Conditional

使用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

java 复制代码
storage:
  type: ${STORAGE_TYPE:local}

设定为local时,启用LocalStorageService

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

设定为aws时,启用AwsStorageService

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

设定为aliyun时,启用AliyunStorageService

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

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

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

本文转载自廖雪峰老师的官方网站 liaoxuefeng.com

相关推荐
铁皮饭盒13 分钟前
Bun执行python代码
前端·javascript·后端
菜鸟谢38 分钟前
Rust 枚举 (enum) 完整核心知识点
后端
晓杰在写后端1 小时前
从0到1实现Balatro游戏后端(9):Blind奖励结算与金币系统实现
后端·游戏开发
Patrick_Wilson1 小时前
幂等到底是什么?从前端视角讲透 SQL、HTTP 与 POST 接口的幂等设计
前端·后端·架构
凌览1 小时前
一人公司别再上 Jenkins,真不值
前端·后端
菜鸟谢1 小时前
Rust 元组与数组内存管理笔记
后端
oil欧哟1 小时前
Codex 最佳实践(超级长文):先搞懂 AI,再用好 AI
前端·人工智能·后端
AskHarries1 小时前
把一个外部系统接成 MCP 工具
后端·程序员
释然小师弟1 小时前
Android开发十年:反思与回顾
android·后端·嵌入式
雪隐1 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地FLUX.2 Klein 的 AI 图片生成
人工智能·后端