0

today I'm learning build API using kotlin and spring boot. In rails and laravel have a "tool" for database seeder, I want to know in kotlin and spring boot, I have been searched on google before and found this answer https://stackoverflow.com/a/45324578/1297435, in spring boot we can use @EventListerner like

@EventListener
    public void userSeeder(ContextRefreshedEvent event) {
        // my query
        // check query size and iteration
}

That's in spring boot, but is there a way in kotlin?

// main/kotlin/com.myapp.api/seeder/UserSeeder.kt
package com.myapp.api.seeder

import org.springframework.context.event.ContextRefreshedEvent
import com.myapp.api.repository.*
import com.myapp.api.model.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
interface EventListener

@Component
class UserSeeder {
    @Autowired
    lateinit var repository: UserRepository

    @EventListener
    fun seedUsername(event: ContextRefreshedEvent) {
        val users = repository.findByUsernameBlank()
        if (users == null || users!!.size <= 0) {
            // 
        } else {
            //
        }
    }
}

@EventListener class doesn't work in kotlin or is it correct?

Error:(15, 6) Kotlin: This class does not have a constructor

itx
  • 1,327
  • 1
  • 15
  • 38
  • 1
    I don't know spring-boot, but why don't you translate that Java code to Kotlin? like `@EventListener fun userSeeder(event : ContextRefreshedEvent) { /* do sth */ }`? This should work exactly the same as the Java code above – msrd0 Oct 14 '18 at 11:58
  • @msrd0 I see, but how can I use `@EventListerner` in kotlin? – itx Oct 14 '18 at 15:03
  • The same way as in Java (at least on methods)? I think the only difference is with properties and file annotations – msrd0 Oct 14 '18 at 15:51
  • @msrd0 I have try implement `@EventListerner` in kotlin but I get error, I've update my question to put my kotlin seeder – itx Oct 15 '18 at 08:42

1 Answers1

1

You probably have an issue because you define EventListener as an interface instead of importing it from org.springframework.context.event. (See interface EventListener just below the imports.

But you your actual question: I typically use org.springframework.boot.ApplicationRunner for such tasks.

import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner

@Component
class UserSeeder(private val repository: UserRepository) : ApplicationRunner {

    override fun run(args: ApplicationArguments) {
        val users = repository.findByUsernameBlank()
        if (users == null || users!!.size <= 0) {
            //
        } else {
            //
        }
    }

}

BTW: I also used constructor based injection.

Michi Gysel
  • 760
  • 6
  • 11