lateinit属性S尚未初始化

时间:2018-12-18 11:39:38

标签: spring-boot kotlin

我要弹簧靴中的 kotlin 在另一个课程中注入一个单人

  

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的结果,但问题没有解决。
如何在Kotlin的伴侣对象中注入服务?

1 个答案:

答案 0 :(得分:1)

为了让Spring注入到伴随对象中,您将需要为伴随对象外部的字段创建一个setter。 WorkingGroup必须是Spring托管的bean,以便Spring自动装配(注入依赖项)。

@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;
   }
}