使用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
:
yaml
storage:
type: ${STORAGE_TYPE:local}
1
2
2
设定为local
时,启用LocalStorageService
:
java
@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "local", matchIfMissing = true)
public class LocalStorageService implements StorageService {
...
}
1
2
3
4
5
2
3
4
5
设定为aws
时,启用AwsStorageService
:
java
@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "aws")
public class AwsStorageService implements StorageService {
...
}
1
2
3
4
5
2
3
4
5
设定为aliyun
时,启用AliyunStorageService
:
java
@Component
@ConditionalOnProperty(value = "storage.type", havingValue = "aliyun")
public class AliyunStorageService implements StorageService {
...
}
1
2
3
4
5
2
3
4
5
注意到LocalStorageService
的注解,当指定配置为local
,或者配置不存在,均启用LocalStorageService
。
可见,Spring Boot提供的条件装配使得应用程序更加具有灵活性。
小结
Spring Boot提供了几个非常有用的条件装配注解,可实现灵活的条件装配。
评论区留言准则:
1. 本评论区禁止传播封建迷信、吸烟酗酒、低俗色情、赌博诈骗等任何违法违规内容。
2. 当他人以不正当方式诱导打赏、私下交易,请谨慎判断,以防人身财产损失。
3. 请勿轻信各类招聘征婚、代练代抽、私下交易、购买礼包码、游戏币等广告信息,谨防网络诈骗。