[英]Kotlin autowired in spring
I'm pretty new to kotlin but done some extensive java before... 我对Kotlin来说还很陌生,但之前做了一些广泛的Java工作...
I tried to use kotlin and java in the same project but it looked very ugly and I didn't like that my classes were separated into two places. 我试图在同一项目中使用kotlin和java,但看起来非常难看,我不喜欢将我的类分成两个地方。 So now my project is 100% kotlin and there are problems...
所以现在我的项目是100%Kotlin,而且有问题...
I keep getting this error message: 我一直收到此错误消息:
lateinit property serviceX has not been initialized
I understand it means that service is not initialized yet, but how do i do initialized it then? 我了解这意味着该服务尚未初始化,但是我该如何初始化呢?
with java and spring, I did @Autowired or injected services in the constructor and was done. 使用java和spring,我在构造函数中执行了@Autowired或注入服务,并完成了。
what I need is for my REST to be able to use serviceX 我需要的是REST能够使用serviceX
@Component
@Path("/super")
open class SuperRest : BaseRest() {
@PUT
@Path("/test")
fun putTest(
@Context securityContext: SecurityContext,
@NotNull selected: String
) {
val user = serviceX(securityContext)
}
}
and in BaseRest I have tried to autowire serviceX first, it was: 在BaseRest中,我尝试首先自动连接serviceX,它是:
@Autowired
protected lateinit var serviceX: ServiceX
then it was just 那只是
@Autowired
lateint var serviceX: ServiceX
then I tried other solutions I found in SO 然后我尝试了在SO中找到的其他解决方案
open class BaseRest @Autowired constructor(
private val serviceX: ServiceX
) { ... }
Why is this? 为什么是这样? I can still use other @autowired services in my rest just fine.
我仍然可以在休息时使用其他@autowired服务。 Just when I try to use them from BaseRest extension i will get
当我尝试从BaseRest扩展中使用它们时,我会得到
lateinit property serviceX has not been initialized
even without any lateinit property, i still somehow get this error.. 即使没有任何lateinit属性,我仍然以某种方式得到此错误。
private var serviceX: ServiceX = ServiceX()
it is still somehow not initialized, please help 它仍然以某种方式未初始化,请帮助
Not sure to understand the 不确定了解
Just when I try to use them from BaseRest extension i will get
当我尝试从BaseRest扩展中使用它们时,我会得到
part, but here is the code I came across and it's working fine as expected. 部分,但这是我遇到的代码,它按预期工作正常。
open class BaseRest {
@Autowired
protected lateinit var serviceX: ServiceX
fun baseFun() {
serviceX.serviceFun(SecurityContextImpl())
}
}
@Component
open class SuperRest : BaseRest() {
fun putTest(
securityContext: SecurityContext,
@NotNull selected: String
) {
baseFun()
val user = serviceX.serviceFun(securityContext)
}
}
Bonus question : Why do you use @PUT and @Path("/test")
annotations and not @PutMapping("/test")
? 奖励问题:为什么使用
@PUT and @Path("/test")
注释而不使用@PutMapping("/test")
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.