@ConditionalOnProperty
来源
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
即: 来源于Spring boot 中的自动化配置部分
实际作用:
通过读取本地配置文件中的值来判断 某些 Bean 或者 配置类 是否加入spring 中。
即 当前类通过 @Component 或者 @Configuration 注册实体到spring 中时,都可以通过 @ConditionalOnProperty 来控制是否加入或者说有无该项。
实际使用
与 @Component 或者 @Configuration 等同级,都置于类上
@ConditionalOnProperty(prefix = "my",name = "config.switch",havingValue = "true")
或
@ConditionalOnProperty(name = "my.kafka.enable", havingValue = "true")
prefix: 为配置前缀,可以没有
name: 如果有前缀则为前缀后面的所有
havingValue: 为配置项的值等于某一值时生效
在配置中如下:
yml 中
my:config:switch: true
properties 中
my.config.switch: true
实例:
@Configuration
@ConditionalOnProperty(prefix = "swagger", name = "enable", havingValue = "true")
public class SwaggerConfig {...........
}