SpringBoot之@ConditionalOnProperty實戰一:線上環境關閉sql日誌打印

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章