环境:springboot2.3.10
需求:有这么一个Bean它被注册的条件是需要满足多个条件下才能被注册。如下
pack:
datasource:
enabled: true
---
pack:
cache:
enabled: true
只有在这两个属性都为true时才注册Bean。
方法1 @ConditionalOnExpression
注解说明:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnExpressionCondition.class)
public @interface ConditionalOnExpression {
/**
* The SpEL expression to evaluate. Expression should return {@code true} if the
* condition passes or {@code false} if it fails.
* @return the SpEL expression
*/
String value() default "true";
}
表达式SpEL表达式 要么返回true,要么返回false。
使用内置的@ConditionalOnExpression表达式条件注解。
@Bean
@ConditionalOnExpression("${pack.datasource.enabled:true} and ${pack.cache.enabled:true}")
public Animal animal() {
return new Animal() ;
}
pack:
datasource:
enabled: true
---
pack:
cache:
enabled: false
只有这两个属性都配置为true时Animal Bean才会被注册。
方式2 AllNestedConditions & AnyNestedCondition
使用AllNestedConditions所有条件都满足的情况下才会注册Bean
public class DataSourceAllCondition extends AllNestedConditions {
public DataSourceAllCondition() {
super(ConfigurationPhase.REGISTER_BEAN) ;
}
public DataSourceAllCondition(ConfigurationPhase configurationPhase) {
super(configurationPhase);
}
@ConditionalOnBean(UsersController.class)
static class ExistClass {
}
@ConditionalOnProperty(prefix = "pack.datasource", name = "enabled", havingValue = "true", matchIfMissing = false)
static class PropertyEnabled {
}
@ConditionalOnProperty(prefix = "pack.cache", name = "enabled", havingValue = "true", matchIfMissing = false)
static class PropertyEnabled {
}
}
@Bean
@Conditional(DataSourceAnyCondition.class)
public Animal animal() {
return new Animal() ;
}
这里只有3个条件都满足了才会注册。当前上下文中存在UsersController Bean,pack.datasource.enabled=true, pack.cache.enabled=true 3个条件同时成立才会被注册。
AnyNestedCondition 只要有一个条件成立就会注册Bean。
public class DataSourceAnyCondition extends AnyNestedCondition {
public DataSourceAnyCondition() {
super(ConfigurationPhase.REGISTER_BEAN) ;
}
public DataSourceAnyCondition(ConfigurationPhase configurationPhase) {
super(configurationPhase);
}
@ConditionalOnProperty(prefix = "pack.datasource", name = "enabled", havingValue = "true", matchIfMissing = false)
static class PropertyEnabled {
}
@ConditionalOnProperty(prefix = "pack.cache", name = "enabled", havingValue = "true", matchIfMissing = false)
static class PropertyEnabled {
}
}
两个条件只要有一个成立即可。
完毕!!!
关注一波呗
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/80010.html