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

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

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

前言

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

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

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

1. 引入依賴(Maven)

根據(jù) Spring Boot 版本選擇對(duì)應(yīng)依賴(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()
                // 文檔標(biāo)題、描述、版本
                .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ā)團(tuán)隊(duì)")
                                .email("dev@example.com")));
    }
}

3. 啟動(dòng)類開啟 Swagger3

在 Spring Boot 啟動(dòng)類上添加@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. 訪問(wèn) Swagger UI

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

二、Swagger3 核心注解詳解

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

1. 接口類注解(Controller 層)

@Tag:描述 Controller 類

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

屬性名作用示例值
name模塊名稱(必填)“用戶管理模塊”
description模塊描述(可選)“包含用戶新增、查詢、刪除接口”
order排序序號(hào)(可選)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操作接口,支持分頁(yè)查詢和條件篩選")
public class UserController {
    // 接口方法...
}

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

@Operation:描述接口方法

定義單個(gè)接口的功能、請(qǐng)求方式等核心信息,是方法級(jí)最核心的注解:

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

@ApiResponses & @ApiResponse:描述接口響應(yīng)

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

  • @ApiResponses:用于包裹多個(gè)@ApiResponse
  • @ApiResponse:?jiǎn)蝹€(gè)響應(yīng)狀態(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ù)錯(cuò)誤(如用戶名為空、格式錯(cuò)誤)"),
        @ApiResponse(responseCode = "500", description = "服務(wù)器異常,新增失敗")
})
public Result<Integer> addUser(@RequestBody UserDTO userDTO) {
    // 業(yè)務(wù)邏輯...
    return Result.success(userId);
}

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

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

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

屬性名作用示例值
name參數(shù)名(必填)“userId”
description參數(shù)描述(可選)“用戶 ID,用于查詢單個(gè)用戶”
required是否必傳(可選)true(默認(rèn) 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è)務(wù)邏輯...
    return Result.success(userVO);
}

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

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

使用示例

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

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

@Schema:描述實(shí)體類 / 字段

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

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

使用示例(實(shí)體類)

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

import lombok.Data;

@Data

@Schema(title = "用戶新增請(qǐng)求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;

}

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

結(jié)合上述注解,實(shí)現(xiàn)一個(gè) “用戶管理” 模塊的完整 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 = "用戶名需唯一,密碼長(zhǎng)度≥8且包含大小寫字母")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "新增成功"),
            @ApiResponse(responseCode = "400", description = "參數(shù)錯(cuò)誤(如用戶名重復(fù))"),
            @ApiResponse(responseCode = "500", description = "服務(wù)器異常")
    })
    public Result<Integer> addUser(@RequestBody @Parameter(description = "用戶新增參數(shù)") UserDTO userDTO) {
        // 模擬業(yè)務(wù)邏輯:生成用戶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) {
        // 模擬查詢結(jié)果
        UserVO userVO = new UserVO();
        userVO.setUserId(userId);
        userVO.setUsername("zhangsan");
        userVO.setAge(25);
        userVO.setEmail("zhangsan@example.com");
        return Result.success(userVO);
    }
}

2. 實(shí)體類(UserDTO & UserVO)

// UserDTO(請(qǐng)求體)
@Data
@Schema(title = "用戶新增DTO", description = "前端新增用戶時(shí)傳遞的參數(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(響應(yīng)體)
@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. 訪問(wèn)文檔效果

啟動(dòng)項(xiàng)目后,訪問(wèn)http://localhost:8080/doc.html,可看到:

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

四、注意事項(xiàng)與最佳實(shí)踐

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

 documentation:

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

五、總結(jié)

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

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

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

相關(guān)文章

  • IDEA 2021版新建Maven、TomCat工程的詳細(xì)教程

    IDEA 2021版新建Maven、TomCat工程的詳細(xì)教程

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

    SpringBoot集成Quartz實(shí)現(xiàn)持久化定時(shí)接口調(diào)用任務(wù)

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

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

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

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

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

    Java中使用qsort對(duì)類進(jìn)行排序的操作代碼

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

    springboot整合RabbitMQ 中的 TTL實(shí)例代碼

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

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

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

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

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

    Java Spring登錄練習(xí)詳解

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

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

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

最新評(píng)論

乃东县| 奈曼旗| 陇南市| 文成县| 都江堰市| 闽侯县| 师宗县| 兴海县| 黄陵县| 武汉市| 板桥市| 巴东县| 肥乡县| 呼伦贝尔市| 泰宁县| 泰顺县| 南康市| 会同县| 都兰县| 睢宁县| 江源县| 临猗县| 邢台县| 西吉县| 稻城县| 工布江达县| 恩施市| 东乌珠穆沁旗| 醴陵市| 德化县| 平乡县| 庆安县| 石嘴山市| 青川县| 钦州市| 宜宾县| 新巴尔虎右旗| 平陆县| 武冈市| 崇礼县| 惠来县|