@ConditionalOnProperty
在 spring boot 中有时候需要控制配置类是否生效,可以使用 @ConditionalOnProperty 注解来控制 @Configuration 是否生效.
示例:
配置类代码
@AutoConfiguration
@ConditionalOnProperty(prefix = "yudao.tenant", value = "enable", havingValue = true) // 允许使用 yudao.tenant.enable=false 禁用多租户
@EnableConfigurationProperties(TenantProperties.class)
public class YudaoTenantAutoConfiguration {
xxxxxxxxxxxxxxxx
}
配置文件代码
yudao:
tenant: # 多租户相关配置项
enable: true
所以当enable=true是,该配置类才会生效
@ConditionalOnProperty源码:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.boot.autoconfigure.condition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Conditional;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnPropertyCondition.class})
public @interface ConditionalOnProperty {
String[] value() default {};
String prefix() default "";
String[] name() default {};
String havingValue() default "";
boolean matchIfMissing() default false;
}
havingValue 和 matchIfMissing 区别:
havingValue
: 表示要匹配的属性值的属性名。当配置文件中该属性的值为指定的值时,类或方法将被条件注解所影响。如果配置文件中未设置该属性,或者属性值不等于指定的值,则类或方法不会被条件注解所影响。matchIfMissing
: 表示在配置文件中未找到该属性时是否匹配。默认为 false,表示只有在配置文件中设置了该属性时才会匹配。如果设置为 true,则即使配置文件中未设置该属性,也会匹配。当配置文件中未找到该属性时,如果matchIfMissing
为 true,则类或方法将被条件注解所影响;如果matchIfMissing
为 false,则类或方法不会被条件注解所影响。
因此,havingValue
和 matchIfMissing
的区别在于,havingValue
用于指定要匹配的属性值,而 matchIfMissing
用于控制类或方法是否在属性未找到时被条件注解所影响。