简体   繁体   中英

Kotlin with Spring DI: lateinit property has not been initialized

I don't get Spring-based setter dependency injection in Kotlin to work as it always terminates with the error message "lateinit property api has not been initialized". I could reduce the problem to the following scenario: There is an interface

interface IApi {
  fun retrieveContent(): String
}

which is implemented by

class Api : IApi {
    override fun retrieveContent() = "Some Content"
}

I want to use the implementation in another class where the dependency injection is supposed to take place:

@Component
class SomeController {
    @Autowired lateinit var api: IApi
    fun printReceivedContent() {
        print(api.retrieveContent())
    }
}

However, the application terminates with the above-mentioned error message. My Spring config looks as follows:

@Configuration
open class DIConfig {
    @Bean
    open fun getApiInstance(): IApi = Api()
}

In the main function I load the application context and call the method:

fun main(args: Array<String>) {
    val context = AnnotationConfigApplicationContext()
    context.register(DIConfig::class.java)
    context.refresh()

    val controller = SomeController()
    controller.printReceivedContent()
}

What is the problem here?

Spring isn't involved if you just call the constructor yourself like that. Same as in Java,

val controller = context.getBean(SomeController::class.java)

Spring Framework 5.0 adds Kotlin extensions , so you could also write either one of

val controller = context.getBean<SomeController>()
val controller: SomeController = context.getBean()

您的 api 目前不是 spring 管理的 bean,请尝试使用 @Service 或 @Component 对其进行注释

The @Autowired is usually added to the setter of a property. So instead of using it for the property, you should explicitly annotate the setter:

@set:Autowired lateinit var api: IApi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM