1

I want inject a singleton in another class by kotlin in 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) }
            }
    }
}

By this code, I get below error:

Caused by: org.zalando.problem.DefaultProblem: Internal Server Error: lateinit property s has not been initialized

I search for this error and found some result like this, but the problem not solved.
How can I inject service in companion object in kotlin?

mgh
  • 921
  • 3
  • 9
  • 37

1 Answers1

1

In order for Spring to inject into a companion object you will need to create a setter for the field outside of the companion object. WorkingGroup will need to be a Spring managed bean in order for Spring to autowire it (inject dependencies).

@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;
   }
}
Dean
  • 1,833
  • 10
  • 28
  • The problem is not solved. I get a hint from **@Autowired**: _autowired members must be defined in valid Spring bean_. @Dean – mgh Dec 18 '18 at 11:57
  • If you make the WorkingGroup a bean too, then it works. – Erik Pragt Dec 18 '18 at 12:46
  • 1
    @mgh if `WorkingGroup` is not a Spring managed bean, how do you create it in your code? Furthermore, how do you expect spring to autowire it? – Dean Dec 18 '18 at 12:51