Kotlin Spring 无法自动装配 @Bean 注释

Aur*_*man 0 spring kotlin

我遇到了 spring 和 kotlin 的问题:

这里是 :

我有一个类 MyConfig 定义为

@Configuration
class MyConfig

   @Bean
   fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
        builder.build()
Run Code Online (Sandbox Code Playgroud)

另一方面,我定义了另一个类 MyService

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

    fun test() {
        // Use restTemplate
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我使用弹簧靴 2.0.1
  • 科特林 1.2.40
  • 在 Java 8 上

那么,我错过了什么吗?

zsm*_*b13 7

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

@Configuration
class MyConfig {

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

}
Run Code Online (Sandbox Code Playgroud)