Spring Boot CommandLineRunner 教程展示了如何使用 CommandLineRunner 接口运行 bean。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
CommandLineRunner
CommandLineRunner
是用于指示当 bean 包含在 SpringApplication 中时应运行的接口。 一个 Spring Boot 应用可以有多个实现CommandLineRunner
的 bean。 可以通过@Order
订购。
Spring Boot CommandLineRunner
示例
以下应用演示了CommandLineRunner
的用法。 它在 H2 内存数据库中创建城市,然后列出它们。
这是项目结构。
pom.xml
这是 Maven pom.xml
文件。 我们使用 H2 数据库和 Spring Data JPA。
resources/application.properties
application.properties
是 Spring Boot 中的主要配置文件。 使用spring.main.banner-mode=off
,我们关闭了 Spring 标语。
com/zetcode/model/City.java
这是City
模型,具有以下属性:id
,name
和population
。
com/zetcode/repository/CityRepository.java
CityRepository
在某个城市的存储库中具有一些通用的 CRUD 操作。
com/zetcode/MyRunner.java
通过实现CommandLineRunner
,将在应用启动后执行MyRunner
类的run()
方法。
MyRunner
也装饰有@Component
,因此也会自动检测并注册。
使用@Autowired
注解,我们将CityRepository
bean 注入到repository
字段中。
在run()
方法中,我们创建三个城市,然后找到所有城市并将其打印到控制台。
com/zetcode/Application.java
Application
是设置 Spring Boot 应用的入口。
我们使用mvn -q spring-boot:run
运行该应用。
在本教程中,我们展示了如何使用CommandLineRunner
接口创建在应用启动时运行的 bean。