【问题标题】:Why the Spring-boot application requires CommandLineRunner to insert new records?为什么 Spring-boot 应用程序需要 CommandLineRunner 插入新记录?
【发布时间】:2019-12-02 23:09:13
【问题描述】:

我正在按照本教程学习 Spring-Boot: Spring Rest Hello World

在最后一步(即步骤 6)中,Spring-boot 应用程序使用以下代码 sn-p 将 3 个 Book 实体添加到 H2 内存数据库:

// init bean to insert 3 books into h2 database.
@Bean
CommandLineRunner initDatabase(BookRepository repository) {
    return args -> {
        repository.save(new Book("A Guide to the Bodhisattva Way of Life", "Santideva", new BigDecimal("15.41")));
        repository.save(new Book("The Life-Changing Magic of Tidying Up", "Marie Kondo", new BigDecimal("9.69")));
        repository.save(new Book("Refactoring: Improving the Design of Existing Code", "Martin Fowler", new BigDecimal("47.99")));
    };
}

我只是不明白为什么教程需要 CommandLineRunner 才能插入 3 Book 记录。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你到底有什么不明白的?为什么要插入 3 本书?为什么要使用命令行运行器来做到这一点?什么是命令行运行器?你读过docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…吗?
  • 我不明白为什么教程需要创建CommandLineRunner来插入记录。这样做有什么具体原因吗?我们可以把逻辑放在 main 方法中,紧跟在“SpringApplication.run(StartBookApplication.class, args);”之后吗?
  • 当然可以。但是你必须查找上下文来获得对 BookRepository 的引用,而不是使用依赖注入,这就是 Spring 的意义所在。
  • 我可以这样说吗? CommandLineRunner 的目的是在 Spring-boot 应用程序启动时添加自定义逻辑?
  • 已开始。我在第一条评论中链接到的文档中的第一句话:如果您需要在 SpringApplication 启动后运行某些特定代码,您可以实现 ApplicationRunner 或 CommandLineRunner 接口。阅读文档。你会学到很多东西。

标签: java spring-boot


【解决方案1】:

它使用之前定义的BookRepository 来插入三个Book 记录。这允许验证服务是否按预期工作。

没有它,在步骤 7 中使用curl 测试服务将不会返回结果。尽管作者本可以组织测试,以便首先执行更新。

这不是开发服务的关键步骤,但它表明有一种与 Spring 组件交互的简单方法。

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 2018-12-03
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多