@ConditionalOnMissingBean的作用

因为在上面没有看到直接的说明都不是很明确,所以给大家看看我的想法:

@ConditionalOnMissingBean 注解可以用于配置类或者 Bean 方法上,用来控制 Bean 的加载条件。当且仅当容器中不存在指定类型的 Bean 时,被标记的 Bean 才会被创建并加入到容器中。

进入@ConditionalOnMissingBean 查看解释:

@Conditional that only matches when no beans meeting the specified requirements are already contained in the BeanFactory. None of the requirements must be met for the condition to match and the requirements do not have to be met by the same bean.
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.
自:
1.0.0
作者:
Phillip Webb, Andy Wilkinson

转化为中文:

@Conditional仅当BeanFactory中已没有满足指定要求的Bean时才匹配。
条件匹配时不需要满足任何要求,相同的Bean也不必满足这些要求。
当放置在@Bean方法上时,Bean类默认为工厂方法的返回类型:
@配置。
公共类MyAutoConfiguration{。
@ConditionalOnMissingBean。
@Bean。
公共MyService myService(){。
..。
}。
}。
在上面的示例中,如果BeanFactory中没有包含类型为MyService的Bean,则条件将匹配。
该条件只能匹配到目前为止已由应用程序上下文处理的Bean定义,因此,强烈建议仅在自动配置类上使用该条件。
如果候选Bean可能是由另一个自动配置创建的,请确保使用此条件的Bean在之后运行。
自:
1.0.0。
作者:
菲利普·韦伯,安迪·威尔金森

@Bean
	@ConditionalOnMissingBean(RedisConnectionDetails.class)
	PropertiesRedisConnectionDetails redisConnectionDetails(RedisProperties properties) {
		return new PropertiesRedisConnectionDetails(properties);
	}

@ConditionalOnMissingBean(RedisConnectionDetails.class) 表示当容器中不存在类型为 RedisConnectionDetails 的 Bean 时,才会创建被该注解标记的 Bean。

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值