二. 設(shè)置開發(fā)環(huán)境。

在開始構(gòu)建 REST API 之前,需準(zhǔn)備以下環(huán)境:

1. 安裝 Java 開發(fā)工具包(JDK)

2. 集成開發(fā)環(huán)境(IDE)

3. 構(gòu)建工具


三. 創(chuàng)建 Spring Boot 項(xiàng)目。

使用 Spring Initializr 快速生成項(xiàng)目:

1. 生成 Spring Boot 項(xiàng)目

  1. 訪問 Spring Initializr。
  2. 配置:

  3. 添加依賴:

  4. 點(diǎn)擊 Generate 下載 .zip 文件。

2. 導(dǎo)入項(xiàng)目到 IDE

  1. 解壓 .zip 文件。
  2. 在 IDE 中以 Maven 項(xiàng)目導(dǎo)入。
  3. IDE 自動(dòng)下載依賴并設(shè)置項(xiàng)目結(jié)構(gòu)。

四. 理解 Spring Boot 項(xiàng)目結(jié)構(gòu)。

典型項(xiàng)目結(jié)構(gòu)如下:

src/main/java/com/example/restapi/
├── RestApiApplication.java // 主應(yīng)用程序入口
├── model/ // 實(shí)體類
├── repository/ // 數(shù)據(jù)庫交互接口
├── service/ // 業(yè)務(wù)邏輯層
├── controller/ // 控制器層
└── resources/application.properties // 配置文件

五. 構(gòu)建 REST API。

以管理 Product 實(shí)體為例:

1. 創(chuàng)建模型(Model)

package com.example.restapi.model;

import jakarta.persistence.*;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and Setters
}

2. 創(chuàng)建存儲(chǔ)庫(Repository)

package com.example.restapi.repository;

import com.example.restapi.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository < Product, Long > {
}

3. 創(chuàng)建服務(wù)層(Service)

package com.example.restapi.service;

import com.example.restapi.model.Product;
import com.example.restapi.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List < Product > getAllProducts() {
        return productRepository.findAll();
    }

    public Optional < Product > getProductById(Long id) {
        return productRepository.findById(id);
    }

    public Product createProduct(Product product) {
        return productRepository.save(product);
    }

    public Product updateProduct(Long id, Product productDetails) {
        Product product = productRepository.findById(id)
                .orElseThrow(() - > new RuntimeException("Product not found"));
        product.setName(productDetails.getName());
        product.setPrice(productDetails.getPrice());
        return productRepository.save(product);
    }

    public void deleteProduct(Long id) {
        Product product = productRepository.findById(id)
                .orElseThrow(() - > new RuntimeException("Product not found"));
        productRepository.delete(product);
    }
}

4. 創(chuàng)建控制器(Controller)

package com.example.restapi.controller;

import com.example.restapi.model.Product;
import com.example.restapi.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping
    public List < Product > getAllProducts() {
        return productService.getAllProducts();
    }

    @GetMapping("/{id}")
    public ResponseEntity < Product > getProductById(@PathVariable Long id) {
        Optional < Product > product = productService.getProductById(id);
        return product.map(ResponseEntity::ok)
                .orElseGet(() - > ResponseEntity.notFound().build());
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }

    @PutMapping("/{id}")
    public ResponseEntity < Product > updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
        Product updatedProduct = productService.updateProduct(id, productDetails);
        return ResponseEntity.ok(updatedProduct);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity < Void > deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}

六. 處理 HTTP 方法。

Spring Boot 提供注解處理常用 HTTP 請(qǐng)求:


七. 錯(cuò)誤處理。

通過全局異常處理器提供一致的錯(cuò)誤響應(yīng):

package com.example.restapi.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity < String > handleRuntimeException(RuntimeException ex, WebRequest request) {
        return new ResponseEntity < > (ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

八. 部署 REST API。

1. 構(gòu)建項(xiàng)目

mvn clean package

2. 運(yùn)行 JAR 文件

java -jar target/restapi-0.0.1-SNAPSHOT.jar

3. 部署到云平臺(tái)


九. 總結(jié)。

通過本指南,您掌握了使用 Java Spring Boot 構(gòu)建 REST API 的核心步驟:

Spring Boot 提供了強(qiáng)大的生態(tài)系統(tǒng)和社區(qū)支持,使其成為構(gòu)建企業(yè)級(jí) RESTful 服務(wù)的理想選擇。


原文鏈接

Index.dev: Build REST API with Java Spring Boot

上一篇:

Python 與 AWS Lambda 構(gòu)建高效無服務(wù)器 REST API 實(shí)戰(zhàn)指南
最后一篇
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)