首页 > 解决方案 > The Right Why Database Seeder with kotlin x spring boot

问题描述

今天我正在学习使用 kotlin 和 spring boot 构建 API。在 rails 和 laravel 中有一个用于数据库播种器的“工具”,我想知道在 kotlin 和 spring boot 中,我之前在 google 上搜索过,在春天找到了这个答案https://stackoverflow.com/a/45324578/1297435引导我们可以@EventListerner使用

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

那是在spring boot中,但是在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类在 kotlin 中不起作用还是正确?

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

标签: spring-bootkotlin

解决方案


您可能会遇到问题,因为您将 EventListener 定义为一个接口,而不是从org.springframework.context.event. (见interface EventListener下面的进口。

但是您的实际问题是:我通常org.springframework.boot.ApplicationRunner用于此类任务。

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 {
            //
        }
    }

}

顺便说一句:我还使用了基于构造函数的注入。


推荐阅读