11.9 启动初始化CommandLineRunner
为了方便测试用,我们在SpringBoot应用启动的时候初始化几条数据到数据库里。Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。这是一个函数式接口:
1. @FunctionalInterface
2. public interface CommandLineRunner {
3. void run(String... args) throws Exception;
4. }
我们只需要创建一个实现接口 CommandLineRunner 的类。很简单,只需要一个类就可以,无需其他配置。 这里我们使用Kotlin的Lambda表达式来写:
1. @Bean
2. fun init(repository: ArticleRepository) = CommandLineRunner {
3. val article: Article = Article()
4. article.author = "Kotlin"
5. article.title = "极简Kotlin教程 ${Date()}"
6. article.content = "Easy Kotlin ${Date()}"
7. repository.save(article)
8. }
