Spring Boot Swagger3常用注解详解与实战

在 Spring Boot 项目开发中,API 文档是前后端协作、项目维护的重要工具。Swagger3(OpenAPI 3.0)作为主流的 API 文档生成工具,通过简单的注解就能快速生成规范化的 API 文档,极大提升开发效率。本文将详细介绍 Spring Boot 整合 Swagger3 的核心注解及实战用法。

一、Swagger3 环境搭建(基础准备)

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

1. 引入依赖(Maven)

根据 Spring Boot 版本选择对应依赖(Spring Boot 2.x/3.x 通用,3.x 需确保 JDK≥11):

java 复制代码
<!-- 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 核心类

创建配置类,通过注解定义文档基本信息和扫描范围:

java 复制代码
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")
                        // 可选:添加联系人信息
                        .contact(new io.swagger.v3.oas.models.info.Contact()
                                .name("开发团队")
                                .email("dev@example.com")));
    }
}

3. 启动类开启 Swagger3

在 Spring Boot 启动类上添加@EnableOpenApi注解(Swagger3 专用,替代 Swagger2 的@EnableSwagger2):

java 复制代码
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

启动项目后,通过以下地址访问 API 文档界面:

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

二、Swagger3 核心注解详解

Swagger3 注解分为接口类注解接口方法注解参数注解实体类注解四大类,以下是最常用的 10 个注解:

1. 接口类注解(Controller 层)

@Tag:描述 Controller 类

用于定义 Controller 的功能模块,相当于接口分组,属性如下:

属性名 作用 示例值
name 模块名称(必填) "用户管理模块"
description 模块描述(可选) "包含用户新增、查询、删除接口"
order 排序序号(可选) 1(数字越小越靠前)

使用示例

java 复制代码
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 接口详细描述(可选) "传入用户信息,创建新用户,返回用户 ID"
method 请求方式(可选) "POST"(默认自动识别)
hidden 是否隐藏接口(可选) false(true 不显示在文档)
@ApiResponses & @ApiResponse:描述接口响应

定义接口的多组响应状态(如成功、参数错误、服务器异常):

  • @ApiResponses:用于包裹多个@ApiResponse
  • @ApiResponse:单个响应状态配置

使用示例

java 复制代码
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 = "参数错误(如用户名为空、格式错误)"),
        @ApiResponse(responseCode = "500", description = "服务器异常,新增失败")
})
public Result<Integer> addUser(@RequestBody UserDTO userDTO) {
    // 业务逻辑...
    return Result.success(userId);
}

3. 参数注解(方法参数 / 请求体)

@Parameter:描述单个参数

用于方法的单个参数(如路径参数、请求参数),支持指定参数说明、是否必传等:

属性名 作用 示例值
name 参数名(必填) "userId"
description 参数描述(可选) "用户 ID,用于查询单个用户"
required 是否必传(可选) true(默认 false)
example 示例值(可选) "1001"

使用示例(路径参数)

java 复制代码
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 = "根据ID查询用户")
public Result<UserVO> getUserById(
        @PathVariable 
        @Parameter(name = "userId", description = "用户唯一ID", required = true, example = "1001") 
        Integer userId) {
    // 业务逻辑...
    return Result.success(userVO);
}
@RequestBody:描述请求体参数

用于标记请求体参数(通常是 JSON 格式),并关联实体类的@Schema注解:

使用示例

java 复制代码
@PostMapping("/update")
@Operation(summary = "更新用户信息")
public Result<Boolean> updateUser(
        @RequestBody 
        @Parameter(description = "用户更新信息,userId必传") 
        UserUpdateDTO userUpdateDTO) {
    // 业务逻辑...
    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"(如邮箱格式校验)

使用示例(实体类)

java 复制代码
import io.swagger.v3.oas.annotations.media.Schema;

import lombok.Data;

@Data

@Schema(title = "用户新增请求DTO", description = "用于接收前端传递的用户新增参数")

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;

}

三、实战案例:完整接口文档示例

结合上述注解,实现一个 "用户管理" 模块的完整 API 文档,效果如下:

1. Controller 层(UserController)

java 复制代码
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 = "参数错误(如用户名重复)"),
            @ApiResponse(responseCode = "500", description = "服务器异常")
    })
    public Result<Integer> addUser(@RequestBody @Parameter(description = "用户新增参数") UserDTO userDTO) {
        // 模拟业务逻辑:生成用户ID
        int userId = 1001;
        return Result.success(userId);
    }

    @GetMapping("/{userId}")
    @Operation(summary = "根据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)

java 复制代码
// UserDTO(请求体)
@Data
@Schema(title = "用户新增DTO", description = "前端新增用户时传递的参数")
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}两个接口
  • 点击接口可查看参数说明、响应状态、实体类字段详情
  • 支持在线调试(填写参数后点击 "发送" 按钮测试接口)

四、注意事项与最佳实践

  1. 生产环境关闭 Swagger 避免接口暴露,在application-prod.yml中配置:
plain 复制代码
springfox:

 documentation:

   enabled: false
  1. 注解属性简化 非必填属性(如description)可根据需求省略,优先保证namesummaryrequired等核心属性。
  2. 参数示例规范化 example属性需填写真实场景的值(如邮箱格式、手机号格式),避免填写 "test" 等无意义值。
  3. 实体类复用 同一实体类在不同接口中(如新增和更新),可通过@Schema(hidden = true)隐藏不需要的字段,无需重复创建实体类。

五、总结

Swagger3 通过简洁的注解,实现了 API 文档的 "代码即文档",极大减少了开发人员维护文档的成本。核心注解包括:

  • 类级别:@Tag(分组描述)
  • 方法级别:@Operation(接口描述)、@ApiResponses(响应描述)
  • 参数级别:@Parameter(单个参数)、@RequestBody(请求体)
  • 实体类级别:@Schema(字段描述)

掌握这些注解后,结合 Spring Boot 可快速生成规范化、可调试的 API 文档,提升前后端协作效率。建议在项目初期就引入 Swagger3,并保持注解与业务逻辑同步更新。

相关推荐
郝学胜-神的一滴3 小时前
QAxios研发笔记(一):在Qt环境下,构建Promise风格的Get请求接口
开发语言·c++·spring boot·qt·ajax·前端框架·软件工程
椎4953 小时前
idea推荐springboot+mybatis+分页查询插件之PageHelper
spring boot·intellij-idea·mybatis
_院长大人_3 小时前
IDEA 实现SpringBoot热部署(HotSwap和DevTools混用)
java·spring boot·intellij-idea
笨蛋不要掉眼泪12 小时前
SpringBoot项目Excel成绩录入功能详解:从文件上传到数据入库的全流程解析
java·vue.js·spring boot·后端·spring·excel
皮皮林55113 小时前
SpringBoot 容器镜像更新只要200k,你敢信???
spring boot
在未来等你16 小时前
Kafka面试精讲 Day 24:Spring Kafka开发实战
java·spring boot·面试·kafka·消息队列·spring kafka·@kafkalistener
龙茶清欢17 小时前
1、Lombok入门与环境配置:理解Lombok作用、配置IDE与构建工具
java·spring boot·spring cloud
龙茶清欢17 小时前
2、Nginx 与 Spring Cloud Gateway 详细对比:定位、场景与分工
java·运维·spring boot·nginx·spring cloud·gateway