首页 > 解决方案 > 如何使用 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。谁能解释这里发生了什么?

标签: springspring-bootkotlin

解决方案


我尝试了您的程序并收到此错误消息:

Configuration problem: @Configuration class 'BugTrackerApplication' may not be final. Remove the final modifier to continue.

所以当我改为BugTrackerApplication

@SpringBootApplication
open class BugTrackerApplication

它按预期工作。


推荐阅读