文
章
目
录
章
目
录
这篇文章讲述了什么是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及其使用示例的全部内容。