先看下源码。首先继承了Condition接口。
Condition接口源码
@FunctionalInterface
public interface Condition {
/**
* Determine if the condition matches.
* @param context the condition context
* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
* or {@link org.springframework.core.type.MethodMetadata method} being checked
* @return {@code true} if the condition matches and the component can be registered,
* or {@code false} to veto the annotated component's registration
*/
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
注释最后两行百度翻译下,作用说的很清楚了。
matches方法返回true,就注入bean,否则,不注入。
简单的使用场景。
如果有个需要注入的组件,只在local环境执行,不在local-2执行。
1.先写一个是否注入的逻辑处理类
public class CheckEnvironmentCondition implements Condition {
/**
* Determine if the condition matches.
*
* @param context the condition context
* @param metadata the metadata of the {@link AnnotationMetadata class}
* or {@link MethodMetadata method} being checked
* @return {@code true} if the condition matches and the component can be registered,
* or {@code false} to veto the annotated component's registration
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
System.out.println("environment:"+environment);
String active = environment.getProperty("spring.profiles.active");
System.out.println("a:"+active);
if("local".equals(active)){
return true;
}else {
return false;
}
}
}
在组件上加入注解@Conditional(CheckEnvironmentCondition.class)
@Configuration
@Slf4j
@EnableScheduling
@Conditional(CheckEnvironmentCondition.class)
public class ConditionalConfigTest {
@Scheduled(cron = "*/5 * * * * ?")
private void updateJob(){
System.out.println("ConditionalConfigTest:"+ LocalDateTime.now());
}
}
local环境,成功执行
local-2环境,就不执行了,注入失败。