【发布时间】: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