我要注入(inject) 一个 单例 在另一个类(class) Kotlin 在 Spring Boot .
S.kt
@Singleton
@Component
class S(
private val userService: UserService,
val companyRepo: CompanyRepo
)
WorkingGroup.kt
class WorkingGroup(
override val name: String = "",
override val desc: String = ""
) : Csv() {
fun isCompatible(ct2: WorkingGroup): Boolean = this == ct2
companion object : ICsvEnumCompanion<WorkingGroup> {
@Inject
private lateinit var s: S
override val VALUES: List<WorkingGroup>
by lazy {
val details = s.user().company.details ?: CompanyDetails()
details.workingGroups.map { WorkingGroup(it.name, it.desc) }
}
}
}
通过这段代码,我得到以下错误:
Caused by: org.zalando.problem.DefaultProblem: Internal Server Error: lateinit property s has not been initialized
我搜索此错误并找到了一些结果,例如 this ,但问题没有解决。
如何在 中注入(inject)服务伴随对象 在 Kotlin ?
最佳答案
为了让 Spring 注入(inject)伴随对象,您需要为伴随对象之外的字段创建一个 setter 。 WorkingGroup
需要成为 Spring 托管 bean 才能让 Spring Autowiring 它(注入(inject)依赖项)。
@Component
class WorkingGroup(
override val name: String = "",
override val desc: String = ""
) : Csv() {
fun isCompatible(ct2: WorkingGroup): Boolean = this == ct2
companion object : ICsvEnumCompanion<WorkingGroup> {
private lateinit var s: S
override val VALUES: List<WorkingGroup>
by lazy {
val details = s.user().company.details ?: CompanyDetails()
details.workingGroups.map { WorkingGroup(it.name, it.desc) }
}
}
@Autowired
fun setS(value: S) {
s = value;
}
}
关于spring-boot - lateinit 属性 S 尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832234/