springboot @ConditionalOnMissingBean注解的作用詳解
@ConditionalOnMissingBean,它是修飾bean的一個注解,主要實現的是,當你的bean被注冊之后,如果而注冊相同類型的bean,就不會成功,它會保證你的bean只有一個,即你的實例只有一個,當你注冊多個相同的bean時,會出現異常,以此來告訴開發(fā)人員。

代碼演示
@Component
public class AutoConfig {
@Bean
public AConfig aConfig() {
return new AConfig("lind");
}
@Bean
@ConditionalOnMissingBean(AMapper.class)
public AMapper aMapper1(AConfig aConfig) {
return new AMapperImpl1(aConfig);
}
@Bean
public AMapper aMapper2(AConfig aConfig) {
return new AMapperImpl2(aConfig);
}
}
因為在aMapper1上面標識了AMapper類型的bean只能有一個實現 @ConditionalOnMissingBean(AMapper.class),所以在進行aMapper2注冊時,系統(tǒng)會出現上面圖上的異常,這是正常的。
當我們把 @ConditionalOnMissingBean(AMapper.class) 去掉之后,你的bean可以注冊多次,這時需要用的@Primary來確定你要哪個實現;一般來說,對于自定義的配置類,我們應該加上@ConditionalOnMissingBean注解,以避免多個配置同時注入的風險。
@Primary標識哪個是默認的bean
@Bean
public AMapper aMapper1(AConfig aConfig) {
return new AMapperImpl1(aConfig);
}
@Bean
@Primary
public AMapper aMapper2(AConfig aConfig) {
return new AMapperImpl2(aConfig);
}
@ConditionalOnProperty
通過其三個屬性prefix,name以及havingValue來實現的,其中prefix表示配置文件里節(jié)點前綴,name用來從application.properties中讀取某個屬性值,havingValue表示目標值。
- 如果該值為空,則返回false;
- 如果值不為空,則將該值與havingValue指定的值進行比較,如果一樣則返回true;否則返回false。
- 返回值為false,則該configuration不生效;為true則生效。
下面代碼演示為配置文件lind.redis.enable為true時才會注冊RedisFactory這個bean
@Configuration
@ConditionalOnProperty(prefix="lind.redis",name = "enable", havingValue = "true")
public class RedisConfig {
@Bean
public RedisMap redisMap(){
return new RedisMapImpl();
}
}
其它注釋及總結
- @ConditionalOnBean // 當給定的在bean存在時,則實例化當前Bean
- @ConditionalOnMissingBean // 當給定的在bean不存在時,則實例化當前Bean
- @ConditionalOnClass // 當給定的類名在類路徑上存在,則實例化當前Bean
- @ConditionalOnMissingClass // 當給定的類名在類路徑上不存在,則實例化當前Bean
到此這篇關于springboot @ConditionalOnMissingBean注解的作用詳解的文章就介紹到這了,更多相關springboot @ConditionalOnMissingBean注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringBoot 注解事務聲明式事務的方式
- springboot2中使用@JsonFormat注解不生效的解決
- SpringBoot中@Pattern注解對時間格式校驗方式
- springboot FeignClient注解及參數
- SpringBoot中@ConfigurationProperties注解的使用與源碼詳解
- SpringBoot2.0整合SpringCloud Finchley @hystrixcommand注解找不到解決方案
- 親測SpringBoot參數傳遞及@RequestBody注解---踩過的坑及解決
- 詳解SpringBoot 快速整合Mybatis(去XML化+注解進階)
- SpringBoot單元測試中@SpyBean使用小結
相關文章
MyBatis游標Cursor在Oracle數據庫上的測試方式
這篇文章主要介紹了MyBatis游標Cursor在Oracle數據庫上的測試方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
Java組件commons fileupload實現文件上傳功能
這篇文章主要為大家詳細介紹了Java組件commons fileupload實現文件上傳功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10

