之前有篇文章Springboot 排除不想加载的配置只是排除,如果有些复杂场景需要根据条件来判断 就需要Spring 支持的另外一种方式 ——@Conditional注解。
借此来看下Spring对于条件注入的支持
public class MetaqCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String property = context.getEnvironment().getProperty("ons.type");
return "metaq".equalsIgnoreCase(property);
}
}
public class MqCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String property = context.getEnvironment().getProperty("ons.type");
return "mq".equalsIgnoreCase(property);
}
}
@Configuration
@Slf4j
public class ConditionalAutoConfig {
@Bean
@Conditional(MqCondition.class)
public Consumer mqConsumerCondition() {
Properties properties = new Properties();
properties.put("AccessKey", "accessKey");
properties.put("SecretKey", "secretKey");
properties.put("ONSAddr", "http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet");
properties.put("ConsumerId", "iotConsumerId");
Consumer consumer = ONSFactory.createConsumer(properties);
log.info("create mq consumer");
return consumer;
}
@Bean
@Conditional(MetaqCondition.class)
public MetaPushConsumer metaPushConsumer() {
MetaPushConsumer consumer = new MetaPushConsumer("consumerId");
log.info("create metaq consumer");
return consumer;
}
}
ons.type=mq
启动项目 log输出 create mq consumer
Conditional 如何解析 看下AnnotatedBeanDefinitionReader.doRegisterBean()
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
//将配置类信息转成AnnotatedGenericBeanDefinition
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
//@Conditional装配条件判断是否跳过注册
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
······
1、@ConditionalOnProperty(prefix = "ons",name = "type",havingValue = "mq")
配置ons.type=mq
生效
2、@ConditionalOnProperty(prefix = "ons",name = {"type","env"},havingValue = "mq")
配置ons.type=mq 同时ons.env=mq
缺一不可才会生效
3、@ConditionalOnProperty(prefix = "ons",name ="type",havingValue = "mq", matchIfMissing=true)
配置 没有也会生效 matchIfMissing=true
1、@ConditionalOnExpression("${ons.type:true}")
配置ons.type=true
时生效
2、@ConditionalOnExpression("'${ons.type}'".equals('mq'))
配置ons.type=mq
时生效
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有