最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring?Boot?Swagger3常用注解詳解與實戰(zhàn)指南

 更新時間:2025年10月30日 11:26:50   作者:VarYa  
Swagger是一個用于設計、構建、文檔化和使用RESTful?Web服務的開源工具,Swagger3是Swagger的最新版本,它提供了許多新功能和改進,這篇文章主要介紹了Spring?Boot?Swagger3常用注解詳解與實戰(zhàn)指南的相關資料,需要的朋友可以參考下

前言

在 Spring Boot 項目開發(fā)中,API 文檔是前后端協(xié)作、項目維護的重要工具。Swagger3(OpenAPI 3.0)作為主流的 API 文檔生成工具,通過簡單的注解就能快速生成規(guī)范化的 API 文檔,極大提升開發(fā)效率。本文將詳細介紹 Spring Boot 整合 Swagger3 的核心注解及實戰(zhàn)用法。

一、Swagger3 環(huán)境搭建(基礎準備)

在使用注解前,需先完成 Spring Boot 與 Swagger3 的整合,步驟如下:

1. 引入依賴(Maven)

根據(jù) Spring Boot 版本選擇對應依賴(Spring Boot 2.x/3.x 通用,3.x 需確保 JDK≥11):

<!-- Swagger3核心依賴 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- 可選:Swagger UI美化依賴(推薦) -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

2. 配置 Swagger3 核心類

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Swagger3Config {
    // 定義API文檔全局信息
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                // 文檔標題、描述、版本
                .info(new Info()
                        .title("Spring Boot Swagger3 API文檔")
                        .description("基于Swagger3的接口文檔示例,包含用戶管理、訂單管理等模塊")
                        .version("v1.0.0")
                        // 可選:添加聯(lián)系人信息
                        .contact(new io.swagger.v3.oas.models.info.Contact()
                                .name("開發(fā)團隊")
                                .email("dev@example.com")));
    }
}

3. 啟動類開啟 Swagger3

在 Spring Boot 啟動類上添加@EnableOpenApi注解(Swagger3 專用,替代 Swagger2 的@EnableSwagger2):

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@SpringBootApplication
@EnableOpenApi // 開啟Swagger3文檔功能
public class Swagger3DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(Swagger3DemoApplication.class, args);
    }
}

4. 訪問 Swagger UI

  • 原生 Swagger UI:http://localhost:8080/swagger-ui/index.html
  • Knife4j 美化 UI(推薦):http://localhost:8080/doc.html

二、Swagger3 核心注解詳解

Swagger3 注解分為接口類注解接口方法注解、參數(shù)注解實體類注解四大類,以下是最常用的 10 個注解:

1. 接口類注解(Controller 層)

@Tag:描述 Controller 類

用于定義 Controller 的功能模塊,相當于接口分組,屬性如下:

屬性名作用示例值
name模塊名稱(必填)“用戶管理模塊”
description模塊描述(可選)“包含用戶新增、查詢、刪除接口”
order排序序號(可選)1(數(shù)字越小越靠前)

使用示例

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
// 描述用戶管理模塊
@Tag(name = "用戶管理模塊", description = "提供用戶CRUD操作接口,支持分頁查詢和條件篩選")
public class UserController {
    // 接口方法...
}

2. 接口方法注解(Controller 方法)

@Operation:描述接口方法

定義單個接口的功能、請求方式等核心信息,是方法級最核心的注解:

屬性名作用示例值
summary接口簡短描述(必填)“新增用戶”
description接口詳細描述(可選)“傳入用戶信息,創(chuàng)建新用戶,返回用戶 ID”
method請求方式(可選)“POST”(默認自動識別)
hidden是否隱藏接口(可選)false(true 不顯示在文檔)

@ApiResponses & @ApiResponse:描述接口響應

定義接口的多組響應狀態(tài)(如成功、參數(shù)錯誤、服務器異常):

  • @ApiResponses:用于包裹多個@ApiResponse
  • @ApiResponse:單個響應狀態(tài)配置

使用示例

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@PostMapping("/add")
@Operation(summary = "新增用戶", description = "注意:用戶名需唯一,密碼需加密傳輸")
@ApiResponses({
        @ApiResponse(responseCode = "200", description = "新增成功,返回用戶ID"),
        @ApiResponse(responseCode = "400", description = "參數(shù)錯誤(如用戶名為空、格式錯誤)"),
        @ApiResponse(responseCode = "500", description = "服務器異常,新增失敗")
})
public Result<Integer> addUser(@RequestBody UserDTO userDTO) {
    // 業(yè)務邏輯...
    return Result.success(userId);
}

3. 參數(shù)注解(方法參數(shù) / 請求體)

@Parameter:描述單個參數(shù)

用于方法的單個參數(shù)(如路徑參數(shù)、請求參數(shù)),支持指定參數(shù)說明、是否必傳等:

屬性名作用示例值
name參數(shù)名(必填)“userId”
description參數(shù)描述(可選)“用戶 ID,用于查詢單個用戶”
required是否必傳(可選)true(默認 false)
example示例值(可選)“1001”

使用示例(路徑參數(shù))

import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@GetMapping("/{userId}")
@Operation(summary = "根據(jù)ID查詢用戶")
public Result<UserVO> getUserById(
        @PathVariable 
        @Parameter(name = "userId", description = "用戶唯一ID", required = true, example = "1001") 
        Integer userId) {
    // 業(yè)務邏輯...
    return Result.success(userVO);
}

@RequestBody:描述請求體參數(shù)

用于標記請求體參數(shù)(通常是 JSON 格式),并關聯(lián)實體類的@Schema注解:

使用示例

@PostMapping("/update")
@Operation(summary = "更新用戶信息")
public Result<Boolean> updateUser(
        @RequestBody 
        @Parameter(description = "用戶更新信息,userId必傳") 
        UserUpdateDTO userUpdateDTO) {
    // 業(yè)務邏輯...
    return Result.success(true);
}

4. 實體類注解(DTO/VO 層)

@Schema:描述實體類 / 字段

用于定義實體類(如 DTO、VO)及其字段的文檔說明,替代 Swagger2 的@ApiModel@ApiModelProperty

屬性名作用示例值
title實體類描述(類級別)“用戶新增請求 DTO”
description字段描述(字段級別)“用戶名,長度 1-20 字符”
required字段是否必傳(可選)true(默認 false)
example字段示例值(可選)“zhangsan”
hidden是否隱藏字段(可選)false(true 不顯示在文檔)
format字段格式(可選)“email”(如郵箱格式校驗)

使用示例(實體類)

import io.swagger.v3.oas.annotations.media.Schema;

import lombok.Data;

@Data

@Schema(title = "用戶新增請求DTO", description = "用于接收前端傳遞的用戶新增參數(shù)")

public class UserDTO {

    @Schema(description = "用戶名(唯一)", required = true, example = "zhangsan", maxLength = 20)

    private String username;

    @Schema(description = "密碼(需加密)", required = true, example = "123456aA", minLength = 8)

    private String password;

    @Schema(description = "用戶年齡", example = "25", minimum = "18", maximum = "60")

    private Integer age;

    @Schema(description = "用戶郵箱", example = "zhangsan@example.com", format = "email")

    private String email;

    // 隱藏不需要在文檔中顯示的字段

    @Schema(hidden = true)

    private String createTime;

}

三、實戰(zhàn)案例:完整接口文檔示例

結合上述注解,實現(xiàn)一個 “用戶管理” 模塊的完整 API 文檔,效果如下:

1. Controller 層(UserController)

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
@Tag(name = "用戶管理模塊", description = "提供用戶新增、查詢、更新、刪除接口")
public class UserController {

    @PostMapping("/add")
    @Operation(summary = "新增用戶", description = "用戶名需唯一,密碼長度≥8且包含大小寫字母")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "新增成功"),
            @ApiResponse(responseCode = "400", description = "參數(shù)錯誤(如用戶名重復)"),
            @ApiResponse(responseCode = "500", description = "服務器異常")
    })
    public Result<Integer> addUser(@RequestBody @Parameter(description = "用戶新增參數(shù)") UserDTO userDTO) {
        // 模擬業(yè)務邏輯:生成用戶ID
        int userId = 1001;
        return Result.success(userId);
    }

    @GetMapping("/{userId}")
    @Operation(summary = "根據(jù)ID查詢用戶")
    public Result<UserVO> getUserById(
            @PathVariable 
            @Parameter(name = "userId", description = "用戶ID", required = true, example = "1001") 
            Integer userId) {
        // 模擬查詢結果
        UserVO userVO = new UserVO();
        userVO.setUserId(userId);
        userVO.setUsername("zhangsan");
        userVO.setAge(25);
        userVO.setEmail("zhangsan@example.com");
        return Result.success(userVO);
    }
}

2. 實體類(UserDTO & UserVO)

// UserDTO(請求體)
@Data
@Schema(title = "用戶新增DTO", description = "前端新增用戶時傳遞的參數(shù)")
public class UserDTO {
    @Schema(description = "用戶名", required = true, example = "zhangsan", maxLength = 20)
    private String username;

    @Schema(description = "密碼", required = true, example = "123456aA", minLength = 8)
    private String password;

    @Schema(description = "年齡", example = "25", minimum = "18")
    private Integer age;
}

// UserVO(響應體)
@Data
@Schema(title = "用戶查詢VO", description = "后端返回給前端的用戶信息")
public class UserVO {
    @Schema(description = "用戶ID", example = "1001")
    private Integer userId;

    @Schema(description = "用戶名", example = "zhangsan")
    private String username;

    @Schema(description = "年齡", example = "25")
    private Integer age;

    @Schema(description = "郵箱", example = "zhangsan@example.com")
    private String email;
}

3. 訪問文檔效果

啟動項目后,訪問http://localhost:8080/doc.html,可看到:

  • 左側菜單顯示 “用戶管理模塊” 分組
  • 展開分組可看到/api/user/add/api/user/{userId}兩個接口
  • 點擊接口可查看參數(shù)說明、響應狀態(tài)、實體類字段詳情
  • 支持在線調試(填寫參數(shù)后點擊 “發(fā)送” 按鈕測試接口)

四、注意事項與最佳實踐

  1. 生產環(huán)境關閉 Swagger避免接口暴露,在application-prod.yml中配置:
springfox:

 documentation:

   enabled: false
  1. 注解屬性簡化非必填屬性(如description)可根據(jù)需求省略,優(yōu)先保證name、summary、required等核心屬性。
  2. 參數(shù)示例規(guī)范化example屬性需填寫真實場景的值(如郵箱格式、手機號格式),避免填寫 “test” 等無意義值。
  3. 實體類復用同一實體類在不同接口中(如新增和更新),可通過@Schema(hidden = true)隱藏不需要的字段,無需重復創(chuàng)建實體類。

五、總結

  • 類級別:@Tag(分組描述)
  • 方法級別:@Operation(接口描述)、@ApiResponses(響應描述)
  • 參數(shù)級別:@Parameter(單個參數(shù))、@RequestBody(請求體)
  • 實體類級別:@Schema(字段描述)

掌握這些注解后,結合 Spring Boot 可快速生成規(guī)范化、可調試的 API 文檔,提升前后端協(xié)作效率。建議在項目初期就引入 Swagger3,并保持注解與業(yè)務邏輯同步更新。

到此這篇關于Spring Boot Swagger3常用注解詳解與實戰(zhàn)指南的文章就介紹到這了,更多相關Spring Boot Swagger3常用注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • IDEA 2021版新建Maven、TomCat工程的詳細教程

    IDEA 2021版新建Maven、TomCat工程的詳細教程

    這篇文章主要介紹了IDEA 2021版新建Maven、TomCat工程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • SpringBoot集成Quartz實現(xiàn)持久化定時接口調用任務

    SpringBoot集成Quartz實現(xiàn)持久化定時接口調用任務

    Quartz是功能強大的開源作業(yè)調度庫,幾乎可以集成到任何?Java?應用程序中,從最小的獨立應用程序到最大的電子商務系統(tǒng),本文將通過代碼示例給大家介紹SpringBoot集成Quartz實現(xiàn)持久化定時接口調用任務,需要的朋友可以參考下
    2023-07-07
  • Spring Boot使用AOP在指定方法執(zhí)行完后執(zhí)行異步處理操作

    Spring Boot使用AOP在指定方法執(zhí)行完后執(zhí)行異步處理操作

    這篇文章主要介紹了Spring Boot使用AOP在指定方法執(zhí)行完后執(zhí)行異步處理操作,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2024-06-06
  • Synchronized?和?ReentrantLock?的實現(xiàn)原理及區(qū)別

    Synchronized?和?ReentrantLock?的實現(xiàn)原理及區(qū)別

    這篇文章主要介紹了Synchronized?和?ReentrantLock?的實現(xiàn)原理及區(qū)別,文章為榮啊主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • Java中使用qsort對類進行排序的操作代碼

    Java中使用qsort對類進行排序的操作代碼

    這篇文章主要介紹了JAVA中如何使用qsort對類進行排序,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • springboot整合RabbitMQ 中的 TTL實例代碼

    springboot整合RabbitMQ 中的 TTL實例代碼

    TTL 是 RabbitMQ 中一個消息或者隊列的屬性,表明一條消息或者該隊列中的所有消息的最大存活時間,單位是毫秒,這篇文章主要介紹了springboot整合RabbitMQ 中的 TTL,需要的朋友可以參考下
    2022-09-09
  • Java利用Spire.PDF for Java實現(xiàn)添加、設置和刪除PDF圖層

    Java利用Spire.PDF for Java實現(xiàn)添加、設置和刪除PDF圖層

    PDF文檔作為信息交換的通用格式,其內容的組織與管理至關重要,而PDF圖層正是實現(xiàn)這一目標的神器,下面小編就為大家詳細講講如何使用Java高效操作PDF圖層吧
    2025-10-10
  • Java?DelayQueue實現(xiàn)延時任務的示例詳解

    Java?DelayQueue實現(xiàn)延時任務的示例詳解

    DelayQueue是一個無界的BlockingQueue的實現(xiàn)類,用于放置實現(xiàn)了Delayed接口的對象,其中的對象只能在其到期時才能從隊列中取走。本文就來利用DelayQueue實現(xiàn)延時任務,感興趣的可以了解一下
    2022-08-08
  • Java Spring登錄練習詳解

    Java Spring登錄練習詳解

    這篇文章主要介紹了Java編程實現(xiàn)spring簡單登錄的練習,具有一定參考價值,需要的朋友可以了解下,希望能夠給你帶來幫助
    2021-10-10
  • 淺析Java編程中枚舉類型的定義與使用

    淺析Java編程中枚舉類型的定義與使用

    這篇文章主要介紹了Java編程中枚舉類型的定義與使用,簡單講解了enum關鍵字與枚舉類的用法,需要的朋友可以參考下
    2016-05-05

最新評論

芒康县| 讷河市| 文水县| 龙川县| 太仆寺旗| 贡山| 石门县| 舟山市| 南丹县| 高青县| 运城市| 永靖县| 临湘市| 西峡县| 安图县| 柳江县| 宁海县| 汉源县| 塘沽区| 驻马店市| 双鸭山市| 香格里拉县| 申扎县| 屯留县| 扶绥县| 甘南县| 噶尔县| 台州市| 剑阁县| 阿拉尔市| 建昌县| 嵊州市| 天祝| 二连浩特市| 老河口市| 仁布县| 岱山县| 蒙山县| 青铜峡市| 鲁山县| 寻乌县|