什么是Spring Boot?

Spring Boot是Spring框架的一個擴展,它簡化了獨立、生產就緒的Spring應用程序的開發。通過提供預配置的設置,Spring Boot減少了樣板代碼,使開發人員能夠專注于業務邏輯。


先決條件

在開始之前,請確保已安裝以下工具和環境:


設置項目

使用Spring Initializr

  1. 訪問 Spring Initializr。
  2. 配置項目參數:
  3. 添加以下依賴:
    -SpringWeb
    -SpringDataJPA

  4. 點擊“生成”按鈕下載項目壓縮包。
  5. 解壓文件并在IDE中打開項目。

創建數據模型

創建一個簡單的數據模型類,用于表示API處理的數據。在本例中,我們將創建一個名為Book的實體類。

package com.example.restapi.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Book {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 private String title;
 private String author;
 private String isbn;

 // Getters and Setters
}

創建存儲庫

創建一個存儲庫接口,繼承JpaRepository,以便處理數據訪問操作。

package com.example.restapi.repository;

import com.example.restapi.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository {
}

創建服務層

服務層封裝了業務邏輯,并與存儲庫交互。以下是服務類的示例:

package com.example.restapi.service;

import com.example.restapi.model.Book;
import com.example.restapi.repository.BookRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {

 private final BookRepository bookRepository;

 public BookService(BookRepository bookRepository) {
 this.bookRepository = bookRepository;
 }

 public List getAllBooks() {
 return bookRepository.findAll();
 }

 public Book getBookById(Long id) {
 return bookRepository.findById(id).orElse(null);
 }

 public Book createBook(Book book) {
 return bookRepository.save(book);
 }

 public void deleteBook(Long id) {
 bookRepository.deleteById(id);
 }
}

創建控制器

創建一個REST控制器,用于處理HTTP請求并將其映射到服務方法。

package com.example.restapi.controller;

import com.example.restapi.model.Book;
import com.example.restapi.service.BookService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {

 private final BookService bookService;

 public BookController(BookService bookService) {
 this.bookService = bookService;
 }

 @GetMapping
 public List getAllBooks() {
 return bookService.getAllBooks();
 }

 @GetMapping("/{id}")
 public Book getBookById(@PathVariable Long id) {
 return bookService.getBookById(id);
 }

 @PostMapping
 public Book createBook(@RequestBody Book book) {
 return bookService.createBook(book);
 }

 @DeleteMapping("/{id}")
 public void deleteBook(@PathVariable Long id) {
 bookService.deleteBook(id);
 }
}

配置應用程序屬性

application.properties文件中配置H2數據庫的連接信息:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

運行應用程序

在IDE中運行主類,或者在終端中執行以下命令:

mvn spring-boot:run

測試API

使用PostmancURL工具測試以下API端點

獲取所有書籍

GET http://localhost:8080/api/books

根據ID獲取書籍

GET http://localhost:8080/api/books/1

創建新書

POST http://localhost:8080/api/books
Content-Type: application/json

{
 "title": "Spring Boot in Action",
 "author": "Craig Walls",
 "isbn": "9781617292545"
}

刪除書籍

DELETE http://localhost:8080/api/books/1

使用DTO優化數據傳輸

在實際開發中,建議使用數據傳輸對象(DTO)來封裝API發送或接收的數據。DTO可以幫助:

  1. 保護敏感信息
  2. 提高性能
  3. 解耦數據模型與API表示
  4. 組織數據結構

以下是一個簡單的DTO示例:

package com.example.restapi.dto;

public class BookDTO {
 private String title;
 private String author;

 // Getters and Setters
}

在服務層和控制器中引入DTO以優化數據傳輸。


總結

通過本指南,您已經學會了如何使用Spring Boot構建一個功能完整的REST API。Spring Boot提供了強大的功能和靈活的配置,適用于各種規模的項目。您可以進一步探索安全性、驗證和錯誤處理等高級功能,以構建更加健壯的API。

原文鏈接: https://medium.com/@pratik.941/building-rest-api-using-spring-boot-a-comprehensive-guide-3e9b6d7a8951

上一篇:

構建RESTful API的10大流行框架

下一篇:

低代碼、無代碼與api自動化:噱頭還是福音?
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費