欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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 文檔生成工具,通過簡(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. 訪問 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ù)說明、是否必傳等:

屬性名作用示例值
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)及其字段的文檔說明,替代 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. 訪問文檔效果

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

  • 左側(cè)菜單顯示 “用戶管理模塊” 分組
  • 展開分組可看到/api/user/add/api/user/{userId}兩個(gè)接口
  • 點(diǎn)擊接口可查看參數(shù)說明、響應(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” 等無意義值。
  3. 實(shí)體類復(fù)用同一實(shí)體類在不同接口中(如新增和更新),可通過@Schema(hidden = true)隱藏不需要的字段,無需重復(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)文章

  • SpringBoot重寫addResourceHandlers映射文件路徑方式

    SpringBoot重寫addResourceHandlers映射文件路徑方式

    這篇文章主要介紹了SpringBoot重寫addResourceHandlers映射文件路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Mybatis-plus獲取雪花算法生成的ID并返回生成ID

    Mybatis-plus獲取雪花算法生成的ID并返回生成ID

    本文主要介紹了Mybatis-plus獲取雪花算法生成的ID并返回生成ID,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-09-09
  • 深入理解Java設(shè)計(jì)模式之策略模式

    深入理解Java設(shè)計(jì)模式之策略模式

    這篇文章主要介紹了JAVA設(shè)計(jì)模式之策略模式的的相關(guān)資料,文中示例代碼非常詳細(xì),供大家參考和學(xué)習(xí),感興趣的朋友可以了解下
    2021-11-11
  • feign調(diào)用第三方接口,編碼定義GBK,響應(yīng)中文亂碼處理方式

    feign調(diào)用第三方接口,編碼定義GBK,響應(yīng)中文亂碼處理方式

    這篇文章主要介紹了feign調(diào)用第三方接口,編碼定義GBK,響應(yīng)中文亂碼處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 從零開始在Centos7上部署SpringBoot項(xiàng)目

    從零開始在Centos7上部署SpringBoot項(xiàng)目

    本文主要介紹了從零開始在Centos7上部署SpringBoot項(xiàng)目,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • SpringBoot中的server.context-path的實(shí)現(xiàn)

    SpringBoot中的server.context-path的實(shí)現(xiàn)

    本文主要介紹了SpringBoot中的server.context-path的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08
  • javaWeb使用servlet搭建服務(wù)器入門

    javaWeb使用servlet搭建服務(wù)器入門

    這篇文章主要為大家詳細(xì)介紹了javaWeb使用servlet搭建服務(wù)器入門,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • JAVA使用geotools讀取shape格式文件的方法

    JAVA使用geotools讀取shape格式文件的方法

    這篇文章主要介紹了JAVA使用geotools讀取shape格式文件的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2017-01-01
  • Spring Boot配置線程池拒絕策略的場(chǎng)景分析(妥善處理好溢出的任務(wù))

    Spring Boot配置線程池拒絕策略的場(chǎng)景分析(妥善處理好溢出的任務(wù))

    本文通過實(shí)例代碼給大家介紹下如何為線程池配置拒絕策略、如何自定義拒絕策略。對(duì)Spring Boot配置線程池拒絕策略的相關(guān)知識(shí)感興趣的朋友一起看看吧
    2021-09-09
  • Java之NIO基本簡(jiǎn)介

    Java之NIO基本簡(jiǎn)介

    這篇文章主要介紹了Java之NIO基本簡(jiǎn)介,文中給大家講到了NIO?與?BIO的比較結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05

最新評(píng)論