@ConditionalOnMissingBean

Posted chuliang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@ConditionalOnMissingBean相关的知识,希望对你有一定的参考价值。

org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean

@Conditional(value={OnBeanCondition.class})
@Target(value={METHOD, TYPE})
@Retention(value=RUNTIME)
@Documented

Conditional that only matches when the specified bean classes and/or names are not already contained in the BeanFactory. 

When placed on a @Bean method, the bean class defaults to the return type of the factory method: 
 @Configuration
 public class MyAutoConfiguration {

     @ConditionalOnMissingBean
     @Bean
     public MyService myService() {
         ...
     }

 }

In the sample above the condition will match if no bean of type MyService is already contained in the BeanFactory. 

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.
Author:Phillip WebbAndy Wilkinson

 

简单一句话就是,如果指定missing的class比如A,那么生成@Bean这个bean的前提条件就是spring工厂没有这个A,如果没有指定missing的bean,那么A就是它自己,也就是一个工厂不能实例化两次这种bean

以上是关于@ConditionalOnMissingBean的主要内容,如果未能解决你的问题,请参考以下文章

Spring@ConditionalOnBean和@ConditionalOnMissingBean有什么区别

Spring@ConditionalOnBean和@ConditionalOnMissingBean有什么区别

Spring@ConditionalOnBean和@ConditionalOnMissingBean有什么区别

SpringBoot总结

@Conditional派生注解

springboot公开课随笔