Swagger笔记

01 Swagger介绍及spring boot集成

Swagger 介绍

Swagger 是一套用于设计、构建、文档化和使用 RESTful API 的开源工具集。它通过自动生成交互式 API 文档,简化了前后端开发者的协作,并支持在线测试 API 接口。Swagger 的核心组件包括:

  1. OpenAPI 规范 (原 Swagger 规范):

    一种与语言无关的 API 描述标准,用于定义 API 的结构、请求/响应格式、参数等。

  2. Swagger UI

    可视化工具,将 OpenAPI 规范转换为交互式网页,支持直接调用 API 接口。

  3. Swagger Editor

    在线编辑器,用于编写和验证 OpenAPI 规范文件(YAML/JSON)。

  4. Swagger Codegen

    根据 OpenAPI 规范生成客户端 SDK 或服务器端存根代码。

优势

自动生成文档 :减少手动编写文档的工作量。

实时测试 :直接在浏览器中调用 API。

规范化设计:推动 API 设计的标准化。


Swagger3 介绍

Swagger3 是 OpenAPI 3.0 规范的实现,相较于 Swagger2(OpenAPI 2.0),它具备以下优势:

  1. 规范升级

    • 支持更丰富的 API 描述能力(如回调、链接、多服务器配置)。

    • 改进的请求/响应模型定义。

  2. 工具更新

    • 使用 Springdoc-OpenAPI 替代已停止维护的 Springfox(Swagger2 的 Spring 集成方案)。

    • 兼容 Spring Boot 2.x/3.x 和 WebFlux。

  3. 注解简化

    • 注解包从 io.swagger.annotations 升级为 io.swagger.v3.oas.annotations

    • 更清晰的注解命名(如 @Tag 替代 @Api)。


Spring Boot 集成 Swagger3(Springdoc-OpenAPI)

环境要求

• Spring Boot 2.x/3.x(推荐 Springdoc 2.x+)

• JDK 8+

步骤 1:添加依赖

pom.xml 中引入依赖:

xml 复制代码
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version> <!-- Spring Boot 3.x 使用 2.x+,Spring Boot 2.x 可用 1.7.x -->
</dependency>
步骤 2:基础配置

创建配置类 SwaggerConfig.java

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 SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("API 文档")
                        .version("1.0")
                        .description("Spring Boot 集成 Swagger3 示例"));
    }
}
步骤 3:使用注解描述 API

在 Controller 和 Model 上添加 OpenAPI 3.0 注解:

Controller 示例

java 复制代码
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户相关操作")
public class UserController {

    @Operation(
        summary = "获取用户列表",
        description = "返回所有用户信息",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取列表"),
            @ApiResponse(responseCode = "404", description = "资源未找到")
        }
    )
    @GetMapping
    public List<User> getUsers() {
        // 业务逻辑
    }
}

Model 示例

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

@Data
@Schema(name = "User", description = "用户实体")
public class User {
    @Schema(description = "用户ID", example = "1")
    private Long id;

    @Schema(description = "用户名", example = "john_doe", requiredMode = Schema.RequiredMode.REQUIRED)
    private String username;
}
步骤 4:访问 Swagger UI

启动应用后,访问以下 URL:

OpenAPI 规范(JSON)http://localhost:8080/v3/api-docs

Swagger UI 界面http://localhost:8080/swagger-ui.html


高级配置

1. 分组显示 API

为不同模块创建分组:

java 复制代码
@Bean
public GroupedOpenApi publicApi() {
    return GroupedOpenApi.builder()
            .group("用户接口")
            .pathsToMatch("/api/users/**")
            .build();
}

@Bean
public GroupedOpenApi adminApi() {
    return GroupedOpenApi.builder()
            .group("管理接口")
            .pathsToMatch("/api/admin/**")
            .build();
}
2. 集成 JWT 认证

配置全局安全方案:

java 复制代码
@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
            .info(new Info().title("API 文档").version("1.0"))
            .components(new Components()
                    .addSecuritySchemes("BearerAuth", 
                        new SecurityScheme()
                            .type(SecurityScheme.Type.HTTP)
                            .scheme("bearer")
                            .bearerFormat("JWT")))
            .addSecurityItem(new SecurityRequirement().addList("BearerAuth"));
}

在接口上添加安全要求:

java 复制代码
@Operation(summary = "创建用户", security = @SecurityRequirement(name = "BearerAuth"))
@PostMapping
public User createUser(@RequestBody User user) {
    // 业务逻辑
}
3. 自定义文档路径

修改 application.properties

properties 复制代码
# 自定义 Swagger UI 路径
springdoc.swagger-ui.path=/docs
# 自定义 OpenAPI JSON 路径
springdoc.api-docs.path=/api-docs

生产环境优化

1. 按环境启用

通过 Profile 控制 Swagger 的启用:

java 复制代码
@Profile({"dev", "test"}) // 仅在开发/测试环境生效
@Configuration
public class SwaggerConfig { ... }
2. 权限控制

结合 Spring Security 限制访问:

java 复制代码
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").hasRole("ADMIN")
            .anyRequest().permitAll()
        );
    return http.build();
}

Swagger3 与 Swagger2 对比

特性 Swagger3(Springdoc) Swagger2(Springfox)
规范支持 OpenAPI 3.0 OpenAPI 2.0
Spring Boot 兼容性 支持 2.x 和 3.x 仅支持 2.x(不兼容 3.x)
维护状态 活跃维护 已停止维护
注解包 io.swagger.v3.oas.annotations io.swagger.annotations
安全性配置 集成更简洁(支持 OAuth2、JWT) 配置复杂
WebFlux 支持

常见问题

1. Swagger UI 页面空白

• 检查依赖是否引入 springdoc-openapi-starter-webmvc-ui

• 确认没有 Spring Security 拦截 /swagger-ui/** 路径。

2. 注解不生效

• 确保 Controller 类在 Spring Boot 组件扫描路径下。

• 使用 @Schema 替代 Swagger2 的 @ApiModelProperty


相关推荐
清风一徐3 小时前
禅道从18.3升级到21.7.6版本
笔记
Jack___Xue3 小时前
LangChain实战快速入门笔记(六)--LangChain使用之Agent
笔记·langchain·unix
零度@3 小时前
SQL 调优全解:从 20 秒到 200 ms 的 6 步实战笔记(附脚本)
数据库·笔记·sql
im_AMBER4 小时前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
其美杰布-富贵-李5 小时前
HDF5文件学习笔记
数据结构·笔记·学习
d111111111d6 小时前
在STM32函数指针是什么,怎么使用还有典型应用场景。
笔记·stm32·单片机·嵌入式硬件·学习·算法
静小谢6 小时前
前后台一起部署,vite配置笔记base\build
前端·javascript·笔记
ask_baidu7 小时前
Doris笔记
android·笔记
IMPYLH8 小时前
Lua 的 IO (输入/输出)模块
开发语言·笔记·后端·lua
2301_783360138 小时前
【学习笔记】关于RNA_seq和Ribo_seq技术的对比和BAM生成
笔记·学习