1. 概述
在本快速教程中,我們將探討如何使用 Spring Boot 創建一個簡單的基於控制枱的應用程序。
2. Maven 依賴
我們的項目依賴於 spring-boot-starter-parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
</parent>
此外,我們還需要添加 spring-boot-starter 依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
3. 命令行應用程序
我們的命令行應用程序包含一個單一的類,SpringBootConsoleApplication.java,它是我們的 Spring Boot 命令行應用程序的主類。
我們使用 Spring 的 @SpringBootApplication 註解在我們的主類上啓用自動配置。
這個類還實現了 Spring 的 CommandLineRunner 接口。 CommandLineRunner 是一個簡單的 Spring Boot 接口,具有 run 方法。 Spring Boot 將在應用程序上下文加載後自動調用實現此接口的所有 Bean 的 run 方法。
以下是我們的命令行應用程序:
@SpringBootApplication
public class SpringBootConsoleApplication
implements CommandLineRunner {
private static Logger LOG = LoggerFactory
.getLogger(SpringBootConsoleApplication.class);
public static void main(String[] args) {
LOG.info("STARTING THE APPLICATION");
SpringApplication.run(SpringBootConsoleApplication.class, args);
LOG.info("APPLICATION FINISHED");
}
@Override
public void run(String... args) {
LOG.info("EXECUTING : command line runner");
for (int i = 0; i < args.length; ++i) {
LOG.info("args[{}]: {}", i, args[i]);
}
}
}我們還應該指定 spring.main.web-application-type=NONE Spring 屬性。該屬性將明確告知 Spring 這不是一個 Web 應用程序。
當執行 SpringBootConsoleApplication 時,我們可以看到以下日誌:
00:48:51.888 [main] INFO c.b.s.SpringBootConsoleApplication - STARTING THE APPLICATION
00:48:52.752 [main] INFO c.b.s.SpringBootConsoleApplication - No active profile set, falling back to default profiles: default
00:48:52.851 [main] INFO o.s.c.a.AnnotationConfigApplicationContext
- Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6497b078: startup date [Sat Jun 16 00:48:52 IST 2018]; root of context hierarchy
00:48:53.832 [main] INFO o.s.j.e.a.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
00:48:53.854 [main] INFO c.b.s.SpringBootConsoleApplication - EXECUTING : command line runner
00:48:53.854 [main] INFO c.b.s.SpringBootConsoleApplication - args[0]: Hello World!
00:48:53.860 [main] INFO c.b.s.SpringBootConsoleApplication - Started SpringBootConsoleApplication in 1.633 seconds (JVM running for 2.373)
00:48:53.860 [main] INFO c.b.s.SpringBootConsoleApplication - APPLICATION FINISHED
00:48:53.868 [Thread-2] INFO o.s.c.a.AnnotationConfigApplicationContext
- Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6497b078: startup date [Sat Jun 16 00:48:52 IST 2018]; root of context hierarchy
00:48:53.870 [Thread-2] INFO o.s.j.e.a.AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown請注意,run方法在應用程序上下文加載完成後調用,但在main方法執行完成之前。
大多數控制枱應用程序只會有一個實現CommandLineRunner接口的類。如果我們的應用程序有多個實現CommandLineRunner接口的類,則可以使用 Spring 的 @Order註解來指定執行順序。
4. 結論
在本文中,我們學習瞭如何使用 Spring Boot 創建一個簡單的基於控制枱的應用。