Spring Boot CommandLineRunner如何使用及使用示例

后端 潘老师 1个月前 (10-27) 34 ℃ (0) 扫码查看

这篇文章讲述了什么是CommandLineRunner以及在Spring Boot中实现或使用它的不同方式。

注:本文基于Spring Boot 3.1.2版本进行测试。

1.什么是CommandLineRunner?

CommandLineRunner是Spring Boot中的一个接口。当一个类实现这个接口时,Spring Boot会在加载应用程序上下文后自动运行其run方法。通常,我们使用CommandLineRunner来执行启动任务,如用户或数据库初始化、播种或其他启动活动。

以下是Spring Boot中运行CommandLineRunner的简化流程:

  • 应用程序启动
  • Spring Boot初始化并配置bean、属性和应用程序上下文
  • CommandLineRunner(或ApplicationRunner)方法被执行
  • 应用程序现在可以处理连接或请求

2.实现CommandLineRunner

2.1 我们可以创建一个@Component bean,它实现了CommandLineRunner接口并重写了run()方法。Spring将在Spring应用程序启动期间运行此代码。

@Component
public class DatabaseInitializer implements CommandLineRunner {

  @Autowired
  BookRepository bookRepository;

  @Override
  public void run(String... args) {

      bookRepository.save(
              new Book("Book A",
                      BigDecimal.valueOf(9.99),
                      LocalDate.of(1982, 8, 31))
      );

      System.out.println("Database initialized!");
  }
}

2.2. 另一种常见的方法是让@SpringBootApplication类直接实现CommandLineRunner接口。

@SpringBootApplication
public class StartApplication2 implements CommandLineRunner {

  public static void main(String[] args) {
      SpringApplication.run(StartApplication2.class, args);
  }

  @Autowired
  BookRepository bookRepository;

  @Override
  public void run(String... args) {

      bookRepository.save(
              new Book("Book A",
                      BigDecimal.valueOf(9.99),
                      LocalDate.of(1982, 8, 31))
      );

      System.out.println("Database initialized!");
  }
}

3.@Bean CommandLineRunner

开发人员将CommandLineRunner注解为@Bean也是常见的做法,Spring也将在Spring应用程序启动期间运行此代码。

@SpringBootApplication
public class StartApplication {

  public static void main(String[] args) {
      SpringApplication.run(StartApplication.class, args);
  }

  @Autowired
  BookRepository bookRepository;

  @Bean
  public CommandLineRunner startup() {

      return args -> {
          bookRepository.save(
                  new Book("Book A",
                          BigDecimal.valueOf(9.99),
                          LocalDate.of(1982, 8, 31))
          );
          System.out.println("Database initialized!");

      };
  }
}

以上就是SpringBoot中如何使用 CommandLineRunner及其使用示例的全部内容。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/10443.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】