NoSuchBeanDefinitionException - SpringBoot 自动装配构造函数包含具有未生成的自动装配声明的参数

NoSuchBeanDefinitionException - SpringBoot autowired constructor contains param that has an autowired declaration that is not being generated

我有以下代码:
这是我第一个 class 将调用

    @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: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

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

我需要帮助来理解问题,所以请不要只是 post 解决方案。

在您的配置中将 RestTemplate 定义为一个 bean class。

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

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

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

容器随后会在创建您的 bean 时注入这些依赖项。

注意,但是,spring容器必须知道如何注入依赖。有很多方法可以教容器这个。最简单的变体是在 @Configuration class 中提供 @Bean 生产者方法。 Spring 容器 "scans" 所有 @Configurations 在容器的开头和 "registers" @Bean 生产者。

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

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

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

   @Configuration
   public class RestTemplateConfig {

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