SpringBoot中@ConditionalOnProperty的使用及作用详解
作者:极光雨雨
这篇文章主要介绍了SpringBoot中@ConditionalOnProperty的使用及作用详解,@ConditionalOnProperty通过读取本地配置文件中的值来判断 某些 Bean 或者 配置类 是否加入spring 中,需要的朋友可以参考下
@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 { ........... }
到此这篇关于SpringBoot中@ConditionalOnProperty的使用及作用详解的文章就介绍到这了,更多相关@ConditionalOnProperty使用及作用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!