spring-boot - 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
解决方案
您可能会遇到问题,因为您将 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 {
//
}
}
}
顺便说一句:我还使用了基于构造函数的注入。
推荐阅读
- glob - Glob 忽略节点测试文件
- javascript - 映射对象,转换为数组,然后转换回对象
- java - 用空字段改造获取对象
- excel - VSTO Excel 加载项自动禁用
- html - 如何在 CSS 中用视频源替换图像源
- ms-access - 在访问中仅使用默认值创建一行
- android - 如何在flutter插件中使用本地aar?
- openssl - OpenSSL 和 BouncyCastle 之间的 ECDSA 密钥大小差异
- c++ - 如何将信号处理程序添加为方法
- google-cloud-platform - Cloud SQL PostgreSQL 是否有可用的逻辑解码插件?