spring注释@ConditionalOnMissingBean有什么作用? [英] What does the spring annotation @ConditionalOnMissingBean do?

查看:3344
本文介绍了spring注释@ConditionalOnMissingBean有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试启动一个使用了该注释的springboot应用程序.当我尝试启动该应用程序时,出现以下错误:

I am trying to start a springboot application where this annotation has been used. When I try to start the application it gives me the following error:

org.springframework.boot.autoconfigure.condition.OnBeanCondition $ BeanTypeDeductionException无法推断com.shutterfly.sbs.platform.SbsPlatformConfigurationClientConfig.getRestTemplate的bean类型

org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanTypeDeductionException Failed to deduce bean type for com.shutterfly.sbs.platform.SbsPlatformConfigurationClientConfig.getRestTemplate

代码:

@ConditionalOnMissingBean
@Bean
public RestTemplate getRestTemplate() {
    return new RestTemplate();
}

推荐答案

The @ConditionalOnMissingBean annotation is used to load a bean only if a given bean is missing:

@Bean
@ConditionalOnMissingBean(SomeBean.class)
public SomeBean otherBean(){
    return new SomeBean();
}

只有在上下文中不存在其他这种类型的bean时,Spring才会加载上述bean.另一方面,如果应用程序上下文中已经存在类型为 SomeBean 的bean,则不会创建上述bean.

The above bean will get loaded by Spring only if there is no other bean of this type present in the context. On the other hand, if there is already a bean of the type SomeBean present in the application context, the above bean will not be created.

使用此批注很方便的一些用例是:

Some use cases where this annotation comes in handy are:

  • 指定一个后备bean,如果不存在相同类型的bean(例如:如果未配置实际数据库,则使用内存数据库)仅作为备份被加载
  • 指定默认Bean,以便在上下文中存在相同类型的更特定的Bean时被覆盖(例如:使用默认的身份验证机制,除非有人决定将其替换为自己的自定义身份验证)

参考: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

这篇关于spring注释@ConditionalOnMissingBean有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆