Kotlin Spring无法自动发送@Bean annoted

时间:2018-04-23 09:35:56

标签: spring kotlin

我遇到了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中的同类架构没有这样的问题。

  • 我使用spring boot 2.0.1
  • kotlin 1.2.40
  • on java 8

那么,我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

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

@Configuration
class MyConfig {

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

}