spring - 如何使用 Spring Boot (Kotlin) 执行 ApplicationRunner
问题描述
这看起来很愚蠢,因为它看起来很简单,但我正在尝试使用 ApplicationRunner 使用虚拟数据初始化我的 Spring Boot 项目。谁能解释为什么这段代码不起作用?我期待它打印到控制台以下内容:
Note(id=1, title=Note 1, text=null, user=user)
Note(id=2, title=Note 2, text=null, user=user)
Note(id=3, title=Note 3, text=null, user=user)
但相反,它根本不打印任何东西。
这是实现:
import com.bhanna.bugtracker.notes.Note
import com.bhanna.bugtracker.notes.NotesRepository
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
@Component
class DataInitializer(val repository: NotesRepository) : ApplicationRunner {
@Throws(Exception::class)
override fun run(args: ApplicationArguments) {
println("This should be printing to the console but it is not")
listOf("Note 1", "Note 2", "Note 3").forEach {
repository.save(Note(title = it, user = "user"))
}
repository.findAll().forEach { println(it) }
}
}
注意在哪里:
@Entity
data class Note(@Id @GeneratedValue var id: Long? = null,
var title: String? = null,
var text: String? = null,
@JsonIgnore var user: String? = null) {
}
@Component
@RepositoryEventHandler(Note::class)
class AddUserToNote {
@HandleBeforeCreate
fun handleCreate(note: Note) {
val username: String = SecurityContextHolder.getContext().getAuthentication().name
println("Creating note: $note with user: $username")
note.user = username
}
}
NoteRepository 是:
@RepositoryRestResource
interface NotesRepository : JpaRepository<Note, Long> {
fun findAllByUser(name: String): List<Note>
}
最后是主文件:
@SpringBootApplication
class BugTrackerApplication
fun main(args: Array<String>) {
runApplication<BugTrackerApplication>(*args)
}
我认为 @Component 注释意味着 spring 将扫描它并执行底层的 run() 函数,因为它正在实现 ApplicationRunner。谁能解释这里发生了什么?
解决方案
我尝试了您的程序并收到此错误消息:
Configuration problem: @Configuration class 'BugTrackerApplication' may not be final. Remove the final modifier to continue.
所以当我改为BugTrackerApplication
:
@SpringBootApplication
open class BugTrackerApplication
它按预期工作。
推荐阅读
- php - Codeigniter 4:如何检测“解密:身份验证失败”
- python - 当你到达句子中的某个字母时如何打破while循环
- c - 为什么我的 Heapify That 看不起用 0 替换值(可能还有其他问题)
- node.js - 来自 Node.JS 的远程 MariaDB 连接出现错误 -4078
- docker-compose - 服务“redis”指的是未定义的卷 abcdrf:无效的撰写项目
- python - SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape , on an image
- python - Python Web Scraping ESPN 团队名册
- java - {1,4,2} 是由 Java 中的原始类型表示的吗?
- python - 使用 yolov5-inference 包时出现运行时错误
- unix - 有没有办法让我的课程在 VSCODE 上自定义 Unix 终端?