[英]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".我在 Kotlin 中没有让基于 Spring 的 setter 依赖注入工作,因为它总是以错误消息“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:我的 Spring 配置如下所示:
@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.如果您像这样自己调用构造函数,则不涉及 Spring。 Same as in Java,和Java一样,
val controller = context.getBean(SomeController::class.java)
Spring Framework 5.0 adds Kotlin extensions , so you could also write either one of Spring Framework 5.0 添加了Kotlin 扩展,因此您也可以编写以下任一
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. @Autowired
通常被添加到@Autowired
的设置器中。 So instead of using it for the property, you should explicitly annotate the setter:因此,不应将其用于属性,而应显式注释 setter:
@set:Autowired lateinit var api: IApi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.