【问题标题】:How to execute ApplicationRunner with Spring Boot (Kotlin)如何使用 Spring Boot (Kotlin) 执行 ApplicationRunner
【发布时间】:2020-06-15 18:54:51
【问题描述】:

这看起来很愚蠢,因为它看起来很简单,但我正在尝试使用 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。谁能解释这里发生了什么?

【问题讨论】:

  • 您遇到的任何具体错误?
  • @SushilBehera 没有错误,只是没有打印到控制台(我更新了问题)。函数run() 没有被执行
  • 你的 main() 是什么样子的?你的包结构是什么?
  • @FLUXparticle 我刚刚在上面添加了它。 (对不起,我试图将代码保持在最低限度,但此时我所有的卡片都在桌子上哈哈)。有什么想法吗?

标签: spring spring-boot kotlin


【解决方案1】:

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

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

所以当我将BugTrackerApplication 更改为:

@SpringBootApplication
open class BugTrackerApplication

它按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2020-07-24
    • 2021-10-24
    • 2017-05-28
    • 2019-11-27
    相关资源
    最近更新 更多