Issue
This seems silly because it looks like such an easy thing but I am trying to initialize my spring boot project with dummy data using the ApplicationRunner. Can anyone explain why this code is not working? I am expecting it to print to the console the following:
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)
but instead it doesn't print anything at all.
Here is the implementation:
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) }
}
}
Where Note is:
@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
}
}
and NoteRepository is:
@RepositoryRestResource
interface NotesRepository : JpaRepository<Note, Long> {
fun findAllByUser(name: String): List<Note>
}
and finally the main file:
@SpringBootApplication
class BugTrackerApplication
fun main(args: Array<String>) {
runApplication<BugTrackerApplication>(*args)
}
I thought the @Component annotation meant spring will scan it and execute the underlying run() function since it is implementing ApplicationRunner. Can anyone explain whats going on here?
Solution
I tried your program and got this error message:
Configuration problem: @Configuration class 'BugTrackerApplication' may not be final. Remove the final modifier to continue.
So when I changed BugTrackerApplication
to:
@SpringBootApplication
open class BugTrackerApplication
it worked as expected.
Answered By - FLUXparticle
Answer Checked By - Marie Seifert (JavaFixing Admin)