1 condition注解的基本使用,不论是由spring实现的还是自定义的,首先要了解的就是它的实现原理,这就要从自定义一个注解开始
第一步,先了解注解可以用在哪些地方,看元注解 @interface
2 @ConditionalOnExpression 表达式值决定是否执行
变量表达式的key取自属性配置文件
数值型和布尔型
@ConditionalOnExpression("${sig1.enabled}==1&&${sig2.enabled:true}")
字符串类型
@ConditionalOnExpression("'${sig3}'.equals('aaa')")
3@ConditionOnProperty 属性值为true时则matches ,这里不用特意写 havingValue="true",默认就是这个值
@ConditionOnProperty(name = "sign4.enable")
4 自定义注解
public class ScanDemoCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return "true".equalsIgnoreCase(conditionContext.getEnvironment().getProperty("sign5.enabled"));
}
}
@Component
@Conditional(ScanDemoCondition.class)
public class ScanDemoBean {
...
}