我遇到了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注释)才会出现此问题,但不会将bean声明为@Component或@Service。
我对纯Java中的同类架构没有这样的问题。
那么,我错过了什么吗?
答案 0 :(得分:3)
您的restTemplate
方法不在MyConfig
类中 - 您已声明一个空类,后跟一个顶级函数。你错过了使该函数成为类中方法的花括号:
@Configuration
class MyConfig {
@Bean
fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
builder.build()
}