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

标签 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,而不是声明为 @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/

相关文章:

scala - 在 Kotlin 中实现 onComplete Scala Future

android - 如何在 kotlin 正则表达式语句中使用正则表达式开始标记 (^)

java - 带有 Spring 和 Redis 的 Vaadin 在缓慢的环境中加载以前的 UI 状态

java - 在 JSP 页面内调试?

spring - JsonMappingException : Can not construct instance of

java - Spring oAuth2 中 OAuth2RestOperations 和 OAuth2RestTemplate 的区别

java - Freemarker:for循环的高级使用

android-studio - 将值传递给Kotlin中的另一个 Activity

android - 将具有动态值的 Firebase 数据库转换为 Kotlin 数据类的最佳实践

kotlin - "intrinsic"实现在 Kotlin 中意味着什么?