【问题标题】:Kotlin Spring could not autowired an @Bean annotedKotlin Spring 无法自动装配和 @Bean 注释
【发布时间】:2018-04-23 09:35:56
【问题描述】:

我遇到了 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 上

那么,我错过了什么吗?

【问题讨论】:

    标签: spring kotlin


    【解决方案1】:

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

    @Configuration
    class MyConfig {
    
       @Bean
       fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
            builder.build()
    
    }
    

    【讨论】:

    • 哇,谢谢它的工作,我花了这么多时间在这上面。看来我还需要学习语言。再次感谢您的快速答复。
    猜你喜欢
    • 2014-06-30
    • 2016-09-27
    • 2012-08-03
    • 2012-12-04
    • 1970-01-01
    • 2015-05-27
    • 2018-06-09
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多