gpt4 book ai didi

spring - Kotlin Spring 无法 Autowiring 和 @Bean 注释

转载 作者:行者123 更新时间:2023-12-05 08:41:27 24 4
gpt4 key购买 nike

我遇到了 spring 和 kotlin 的问题:

在这里:

我有一个这样定义的类 MyConfig

@Configuration
class MyConfig

@Bean
fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
builder.build()

在另一边,我定义了另一个类 MyService

@Component
class MyService constructor(private val restTemplate: RestTemplate) {

fun test() {
// Use restTemplate
}
}

但我得到的只是以下消息:

Description:

Field restTemplate in my.package.MyService required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

此问题仅发生在@Configuration 类(使用@Bean 注释)中定义的 bean,而不是声明为 @Component 或 @Service 的 bean。

我对纯 Java 中的同类架构没有这样的问题。

  • 我使用的是spring boot 2.0.1
  • Kotlin 1.2.40
  • 在 Java 8 上

那么,我是不是漏掉了什么?

最佳答案

您的 restTemplate 方法不在您的 MyConfig 类中 - 您已经声明了一个空类,后跟一个顶级函数。您缺少使函数成为类内部方法的大括号:

@Configuration
class MyConfig {

@Bean
fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
builder.build()

}

关于spring - Kotlin Spring 无法 Autowiring 和 @Bean 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49977772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com