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

IT 文章2年前 (2023)发布 小编
0 0 0

这篇文章讲述了什么是CommandLineRunner以及在Spring Boot中实现或使用它的不同方式。[v_blue]注:本文基于Spring Boot 3.1.2版本进行测试。[/v_blue]

1.什么是CommandLineRunner?

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

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

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

  • 应用程序启动
  • 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及其使用示例的全部内容。

ad

AI 工具导航

优网导航旗下AI工具导航,精选全球千款优质 AI 工具集

© 版权声明

相关文章

暂无评论

暂无评论...