1、知识点:SpringBoot根据条件,判断是否注入指定的Bean:

@ConditionalOnBean  当容器有指定Bean的条件下
@ConditionalOnClass  当容器有指定类的条件下
@ConditionalOnExpression 基于SpEL表达式作为判断条件
@ConditionalOnJava 基于JVM版本作为判断条件
@ConditionalOnJndi 在JDNI存在的条件下查找指定位置
@ConditionalOnMissingBean 当容器没有指定Bean的情况下
@ConditionalOnMissingClass 当容器没有指定类的情况下
@ConditionalOnNotWebApplication 当前项目不是Web项目的条件下
@ConditionalOnProperty 指定的属性是否有指定的值
@ConditionalOnResource 类路径是否有指定的值
@ConditionalOnSingleCandidate 当前指定Bean在容器中只有一个,或者虽然有多个但是指定首选Bean
@ConditionalOnWebApplication 当前项目是Web项目的情况下

2、实战:根据properties配置文件中的属性值来决定注入哪个Bean:

//mybatis-plus 性能分析插件,控制打印sql,不注入就不打印sql
@ConditionalOnProperty(prefix = "sql" ,name="performanceInterceptor",havingValue = "true")
@Bean
public PerformanceInterceptor performanceInterceptor() {
    return new PerformanceInterceptor();
}

3、对应properties配置文件添加配置:

需要打印就true-->注入对应的Bean(打印sql)
sql.performanceInterceptor=true
不需要打印就false-->不注入对应的Bean(不打印sql)
sql.performanceInterceptor=false

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐