使用 Gradle 構建 Spring Boot REST 應用程序

在本教學中,我們將使用Spring Boot和Gradle來建立一個簡單的RESTful網路服務。Spring Boot能輕鬆創建獨立的、生產級的基於Spring的應用程序,而Gradle是一個強大的構建工具,簡化了構建過程。

什麼是REST?

REST,即Representational State Transfer,是一套確保你的API具有互操作性、可擴展性和可維護性的架構原則。想像搭建樂高積木——只要遵循RESTful指南,不同的應用程序可以無縫地與你的API互動,就像樂高積木無論出自哪個系列都能輕鬆拼接在一起。

什麼是Spring Boot?

Spring Boot 是一個簡化開發流程的強大框架。將其視為一個預先配置的工具包,裝滿了組件和功能,節省了你在設置應用程序基礎設施上的時間和精力。你可以專注於編寫API的核心邏輯,而不會被模板代碼所困擾。

準備好釋放你的內在API開發者潛力了嗎?本指南將指導你使用流行的構建工具Gradle創建你的第一個Spring Boot REST應用程序。無論你是經驗豐富的Java程序員還是剛開始探索,這一步步的旅程將為你提供構建動態和互動式網路服務所需的基礎知識。

關鍵要點

  • 使用Spring Boot建立RESTful API: Spring Boot是一個廣受歡迎的Java框架,它簡化了開發RESTful API的過程。它提供了許多即開即用的功能,例如自動配置和依賴注入,這能夠節省您大量的時間和精力。
  • 理解RESTful API的核心概念: REST代表表現層狀態轉移。它是一套建築原則,確保您的API具有互操作性、可擴展性和可維護性。RESTful API的一些關鍵概念包括資源表示、HTTP方法和狀態碼。
  • 實現基本的CRUD操作: CRUD代表創建、讀取、更新和刪除。這些是您需要在API端點中實現的基本操作,以便用戶能夠與您的數據互動。
  • 徹底測試您的API: 在部署到生產環境之前,徹底測試您的API是非常重要的。這將幫助您確保它按預期工作,並且沒有任何錯誤。
  • 探索進階功能: 隨著您對Spring Boot和RESTful API的熟悉程度提高,您可以探索更多進階功能,如數據管理、安全性和認證。

通過結合REST的力量與Spring Boot的簡化方法,您將能夠創建高效且用戶友好的API,這些API可以無縫地與其他應用程序集成。那麼,您準備好利用Spring Boot和Gradle解鎖RESTful API的潛力了嗎?讓我們開始吧!

先決條件

  • Java Development Kit (JDK) 11 已安裝
  • 最新版 Gradle 已安裝
  • 基本理解 Java 與 Spring 概念

步驟 1: 設置專案

開始專案前,需執行以下三個步驟。

  • 打開終端機或命令提示字元
  • 建立新專案目錄
  • 進入專案目錄
  • 初始化基本 Spring Boot 專案結構

Shell

 

mkdir spring-boot-rest-gradle
cd spring-boot-rest-gradle
gradle init --type spring-boot

步驟 2: 建立 Spring Boot 專案

請編輯目錄中現有的 build.gradle 檔案,內容如下。

Groovy

 

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

此設置建立了一個包含必要依賴的基本 Spring Boot 專案。

步驟 3: 建立 REST 控制器

src/main/java/com/example 目錄下建立一個名為 HelloController.java 的新檔案,內容如下:

Java

 

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class HelloController {

    private final List<String> messages = new ArrayList<>();

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }

    @GetMapping("/messages")
    public List<String> getMessages() {
        return messages;
    }

    @PostMapping("/messages")
    public String addMessage(@RequestBody String message) {
        messages.add(message);
        return "Message added: " + message;
    }

    @PutMapping("/messages/{index}")
    public String updateMessage(@PathVariable int index, @RequestBody String updatedMessage) {
        if (index < messages.size()) {
            messages.set(index, updatedMessage);
            return "Message updated at index " + index + ": " + updatedMessage;
        } else {
            return "Invalid index";
        }
    }

    @DeleteMapping("/messages/{index}")
    public String deleteMessage(@PathVariable int index) {
        if (index < messages.size()) {
            String removedMessage = messages.remove(index);
            return "Message removed at index " + index + ": " + removedMessage;
        } else {
            return "Invalid index";
        }
    }
}

此控制器定義了 GET、POST、PUT 和 DELETE 操作的端點,用於處理簡單的訊息列表。

步驟 4: 執行應用程式

打開終端機或命令提示字元並運行以下命令:

Java

 

./gradlew bootRun

在瀏覽器中訪問 http://localhost:8080/api/hello 以檢查初始端點。您可以使用 curl、Postman 或其他 REST 客戶端工具測試其他端點。

步驟 5: 編寫測試案例

src/test/java/com/example目錄下創建一個名為HelloControllerTest.java的新文件,內容如下:

Java

 

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    public void setUp() {
        // 每次測試前清除消息
        // 這確保每次測試處於乾淨狀態
        // 或者,您可以使用測試數據庫或模擬數據
        // 根據您的需求
        HelloController messagesController = new HelloController();
        messagesController.getMessages().clear();
    }

    @Test
    public void testSayHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Hello, Spring Boot!"));
    }

    @Test
    public void testGetMessages() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/messages"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(0)));
    }

    @Test
    public void testAddMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Test Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message added: Test Message"));
    }

    @Test
    public void testUpdateMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Initial Message\""));

        mockMvc.perform(MockMvcRequestBuilders.put("/api/messages/0")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Updated Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message updated at index 0: Updated Message"));
    }

    @Test
    public void testDeleteMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Message to Delete\""));

        mockMvc.perform(MockMvcRequestBuilders.delete("/api/messages/0"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message removed at index 0: Message to Delete"));
    }
}

這些測試案例使用Spring Boot的測試功能來模擬HTTP請求並驗證REST控制器的行為。

步驟6: 運行測試

打開終端或命令提示符並運行以下命令以執行測試:

Java

 

./gradlew test 

審查測試結果以確保所有測試成功通過。

結論

恭喜!您已成功使用Spring Boot和Gradle創建了一個具有CRUD操作的基本RESTful Web服務。本教程涵蓋了GET、POST、PUT和DELETE操作端點的實現以及相應的測試案例。

附加說明:

  • 這是一個非常基本的示例。您可以通過創建更多端點、處理不同的HTTP方法(POST、PUT、DELETE)以及添加數據管理等功能來擴展它。
  • 考慮使用JUnit等框架為您的控制器添加單元測試。
  • 您可以利用Spring Initializr (https://start.spring.io/) 快速生成包含額外依賴與配置的專案。

若欲進一步學習,請參考以下資源:

記住,這只是您Spring Boot旅程的起點!持續探索並打造令人驚艷的應用程式。

Source:
https://dzone.com/articles/build-your-first-spring-boot-rest-application-with