ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Spring Boot `CommandLineRunner`教程 > 原文: [http://zetcode.com/springboot/commandlinerunner/](http://zetcode.com/springboot/commandlinerunner/) 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 内存数据库中创建城市,然后列出它们。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ │ MyRunner.java │ │ ├───model │ │ │ City.java │ │ └───repository │ │ CityRepository.java │ └───resources │ application.properties └───test └───java ``` 这是项目结构。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>springbootcommandlinerunner</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 这是 Maven `pom.xml`文件。 我们使用 H2 数据库和 Spring Data JPA。 `resources/application.properties` ```java spring.main.banner-mode=off ``` `application.properties`是 Spring Boot 中的主要配置文件。 使用`spring.main.banner-mode=off`,我们关闭了 Spring 横幅。 `com/zetcode/model/City.java` ```java package com.zetcode.model; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "cities") public class City { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int population; public City() { } public City(String name, int population) { this.name = name; this.population = population; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.id); hash = 79 * hash + Objects.hashCode(this.name); hash = 79 * hash + this.population; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final City other = (City) obj; if (this.population != other.population) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return Objects.equals(this.id, other.id); } @Override public String toString() { var builder = new StringBuilder(); builder.append("City{id=").append(id).append(", name=") .append(name).append(", population=") .append(population).append("}"); return builder.toString(); } } ``` 这是`City`模型,具有以下属性:`id`,`name`和`population`。 `com/zetcode/repository/CityRepository.java` ```java package com.zetcode.repository; import com.zetcode.model.City; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CityRepository extends CrudRepository<City, Long> { } ``` `CityRepository`在某个城市的存储库中具有一些通用的 CRUD 操作。 `com/zetcode/MyRunner.java` ```java package com.zetcode; import com.zetcode.model.City; import com.zetcode.repository.CityRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(MyRunner.class); @Autowired private CityRepository repository; @Override public void run(String... args) throws Exception { repository.deleteAll(); repository.save(new City("Bratislava", 432000)); repository.save(new City("Budapest", 1759000)); repository.save(new City("Prague", 1280000)); repository.findAll().forEach((city) -> { logger.info("{}", city); }); } } ``` 通过实现`CommandLineRunner`,将在应用启动后执行`MyRunner`类的`run()`方法。 ```java @Component public class MyRunner implements CommandLineRunner { ``` `MyRunner`也装饰有`@Component`,因此也会自动检测并注册。 ```java @Autowired private CityRepository repository; ``` 使用`@Autowired`注解,我们将`CityRepository` bean 注入到`repository`字段中。 ```java @Override public void run(String... args) throws Exception { repository.save(new City("Bratislava", 432000)); repository.save(new City("Budapest", 1759000)); repository.save(new City("Prague", 1280000)); repository.findAll().forEach((city) -> { logger.info("{}", city); }); ``` 在`run()`方法中,我们创建三个城市,然后找到所有城市并将其打印到控制台。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`是设置 Spring Boot 应用的入口。 我们使用`mvn -q spring-boot:run`运行该应用。 在本教程中,我们展示了如何使用`CommandLineRunner`接口创建在应用启动时运行的 bean。 您可能也对相关教程感兴趣: [Spring Boot `@Order`教程](/springboot/order/), [Spring Boot `@Repository`教程](/springboot/repository/), [Java 教程](/lang/java/)或列出了[全部 Spring 入门教程](/all/#springboot)。