【问题标题】:NoSuchBeanDefinitionException - SpringBoot autowired constructor contains param that has an autowired declaration that is not being generatedNoSuchBeanDefinitionException - SpringBoot 自动装配构造函数包含具有未生成的自动装配声明的参数
【发布时间】:2020-01-26 15:05:12
【问题描述】:

我有以下代码:
这是我的第一堂课,会调用

    @Component
    class DefaultBridge @Autowired constructor(
            private val clientConfig: Config,
            private val client: world.example.Client
    ) : Bridge {

        override fun doEpicStuff(): String {
            val request = createRequest(...)
            val response = client.makeCall(request)
            return response.responseBody
        }
    }

正在使用的客户端 (world.example.Client) 具有以下代码:

public class Client {

@Autowired
private RestTemplate restTemplate;

public Response makeCall(Request request) {
    restTemplate.exchange(....)
}

}

运行代码时。我收到以下错误:

NoSuchBeanDefinitionException: 没有符合条件的 bean 类型 'org.springframework.web.client.RestTemplate' 可用:预计在 至少 1 个符合自动装配候选资格的 bean。依赖 注释: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

  1. 自动装配构造函数时,我应该在哪里声明 bean?
  2. 为什么spring不会自动创建bean?

我需要帮助理解问题,所以请不要只发布解决方案。

【问题讨论】:

    标签: spring spring-boot dependency-injection autowired spring-bean


    【解决方案1】:

    使用 Spring 依赖注入,您可以注入 bean 的实例。

    在 Spring 中,它被称为控制反转 (IoC) 原则。 IoC 也称为依赖注入 (DI)。

    您可以使用成员变量或构造变量为您的 bean 定义依赖项。有不同的可能性,例如@Autowire 作为成员变量的注释,如您的用法。

    然后容器在创建 bean 时注入这些依赖项。

    注意,但是,spring容器需要知道依赖是如何被注入的。有很多方法可以教容器这一点。最简单的变体是在@Configuration 类中提供@Bean 生产者方法。 Spring 容器在容器开始时“扫描”所有 @Configurations 并“注册”@Bean 生产者。

    没有人为RestTemplate 制作过制作人。不是 Spring self,也没有其他 lib。对于您使用的许多其他 bean,这已经完成,而不是 RestTemplate。您必须为RestTemplate 提供@Bean 生产者。

    在新的@Configuration 或您现有的@Configuration 中执行此操作。

    @Configuration 表示一个类声明了一个或多个@Bean 方法,并且可以由 Spring 容器处理以在运行时为这些 bean 生成 bean 定义和服务请求,例如:

       @Configuration
       public class RestTemplateConfig {
    
             @Bean
             public RestTemplate restTemplate() {
                 // New instance or more complex config 
                 return new RestTemplate();
             }
         }
    

    【讨论】:

    • 我浏览了更多教程,得到了完全相同的解决方案。非常感谢您的解释和帮助。我真的很感激:)
    • @Eddie 记得如果它满足您的问题,请接受答案。
    【解决方案2】:

    将 RestTemplate 定义为配置类中的 bean。

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2014-03-15
      • 2012-05-06
      • 1970-01-01
      • 2018-07-05
      • 2021-02-11
      • 2014-09-29
      • 1970-01-01
      • 2018-11-09
      相关资源
      最近更新 更多