Spring Boot 快速入門



本章將教你如何使用 Maven 和 Gradle 建立 Spring Boot 應用程式。

先決條件

你的系統需要滿足以下最低要求才能建立 Spring Boot 應用程式:

  • Java 17
  • Maven 3.6.3
  • Gradle 7.5

Spring Boot CLI

Spring Boot CLI 是一個命令列工具,它允許我們執行 Groovy 指令碼。這是使用 Spring Boot 命令列介面建立 Spring Boot 應用程式最簡單的方法。你可以在命令提示符本身建立、執行和測試應用程式。

本節解釋了手動安裝 Spring Boot CLI 的步驟。如需更多幫助,請訪問以下連結:https://docs.springframework.tw/spring-boot/installing.html

你也可以從 Spring 軟體倉庫下載 Spring CLI 分發版:https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-cli/3.3.3/spring-boot-cli-3.3.3-bin.zip

對於手動安裝,你需要使用以下兩個存檔檔案之一:

  • spring-boot-cli-3.3.3-bin.zip

  • spring-boot-cli-3.3.3-bin.tar.gz

下載後,解壓存檔檔案並按照 install.txt 檔案中的步驟操作。請注意,它不需要任何環境設定。

在 Windows 中,在命令提示符中進入 Spring Boot CLI 的 **bin** 目錄,並執行命令 **spring --version** 以確保 Spring CLI 正確安裝。執行命令後,你將看到如下所示的 Spring CLI 版本:

E:\spring-3.3.3\bin&t; spring --version
Spring CLI v3.3.3
E:\spring-3.3.3\bin>

使用 Spring Boot CLI 建立歡迎訊息 Web 應用程式

E:\spring-3.3.3\bin> spring init --build maven -a test
Using service at https://start.spring.io
Content saved to 'test.zip'
E:\spring-3.3.3\bin>

現在你可以檢查到一個基於maven的spring boot專案已建立,其中包含以下pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.3.3</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.example</groupId>
   <artifactId>test</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>
   <url/>
   <licenses>
      <license/>
   </licenses>
   <developers>
      <developer/>
   </developers>
   <scm>
      <connection/>
      <developerConnection/>
      <tag/>
      <url/>
   </scm>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

以及一個充當主應用程式類的Java類。

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @RequestMapping("/")
	String home() {
		return "Hello World!";
	}
}

讓我們在pom.xml中新增spring boot starter web依賴項。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

以及帶有端點來列印“歡迎來到 Tutorialspoint!”的DemoApplication.java。

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @GetMapping("/")
   String home() {
      return "Welcome to Tutorialspoint!";
   }
}

現在使用maven命令 **mvn spring-boot:run** 執行應用程式,如下所示:

E:\spring-3.3.3\bin\test>mvn spring-boot:run

執行命令後,所需的依賴項將自動下載,它將在 Tomcat 8080 埠啟動應用程式,如下面的螢幕截圖所示:

[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:test >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot:3.3.3:run (default-cli) > test-compile @ test >>>
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ test ---
[INFO] Copying 1 resource from src\main\resources to target\classes
[INFO] Copying 0 resource from src\main\resources to target\classes
[INFO]
[INFO] --- compiler:3.13.0:compile (default-compile) @ test ---
[INFO] Recompiling the module because of added or removed source files.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target\classes
[INFO]
[INFO] --- resources:3.3.1:testResources (default-testResources) @ test ---
[INFO] skip non existing resourceDirectory E:\spring-3.3.3\bin\test\src\test\resources
[INFO]
[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ test ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target\test-classes
[INFO]
[INFO] <<< spring-boot:3.3.3:run (default-cli) < test-compile @ test <<<
[INFO]
[INFO]
[INFO] --- spring-boot:3.3.3:run (default-cli) @ test ---
Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-buildpack-platform/3.3.3/spring-boot-buildpack-platform-3.3.3.pom
...
[INFO] Attaching agents: []

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.3)

2024-09-02T16:30:13.931+05:30  INFO 19320 --- [demo] [           main] com.example.test.DemoApplication         : Starting DemoApplication using Java 21.0.2 with PID 19320 (E:\spring-3.3.3\bin\test\target\classes started by Tutorialspoint in E:\spring-3.3.3\bin\test)
2024-09-02T16:30:13.937+05:30  INFO 19320 --- [demo] [           main] com.example.test.DemoApplication         : No active profile set, falling back to 1 default profile: "default"
2024-09-02T16:30:15.753+05:30  INFO 19320 --- [demo] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-09-02T16:30:15.801+05:30  INFO 19320 --- [demo] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-09-02T16:30:15.801+05:30  INFO 19320 --- [demo] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.28]
2024-09-02T16:30:15.975+05:30  INFO 19320 --- [demo] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-09-02T16:30:15.975+05:30  INFO 19320 --- [demo] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1946 ms
2024-09-02T16:30:16.625+05:30  INFO 19320 --- [demo] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2024-09-02T16:30:16.636+05:30  INFO 19320 --- [demo] [           main] com.example.test.DemoApplication         : Started DemoApplication in 3.707 seconds (process running for 4.316)

Tomcat啟動後,訪問瀏覽器並輸入URL **https://:8080/**,你將看到如下所示的輸出。

Hello Spring Boot
廣告