当前位置: 首页 > article >正文

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 中引入依赖:

<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

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 示例

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 示例

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

为不同模块创建分组:

@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 认证

配置全局安全方案:

@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"));
}

在接口上添加安全要求:

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

修改 application.properties

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

生产环境优化

1. 按环境启用

通过 Profile 控制 Swagger 的启用:

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

结合 Spring Security 限制访问:

@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.0OpenAPI 2.0
Spring Boot 兼容性支持 2.x 和 3.x仅支持 2.x(不兼容 3.x)
维护状态活跃维护已停止维护
注解包io.swagger.v3.oas.annotationsio.swagger.annotations
安全性配置集成更简洁(支持 OAuth2、JWT)配置复杂
WebFlux 支持

常见问题

1. Swagger UI 页面空白

• 检查依赖是否引入 springdoc-openapi-starter-webmvc-ui
• 确认没有 Spring Security 拦截 /swagger-ui/** 路径。

2. 注解不生效

• 确保 Controller 类在 Spring Boot 组件扫描路径下。
• 使用 @Schema 替代 Swagger2 的 @ApiModelProperty



http://www.kler.cn/a/580321.html

相关文章:

  • C#中的【Obsolete】属性Attribute
  • MySQL初阶 | 库的操作
  • PostgreSQL 的登陆方式(本地和远程)
  • 《人月神话》:软件工程的成本寓言与生存法则
  • postgresql使用mysql_fdw连接mysql
  • 大白话如何使用 CSS 实现响应式布局?请列举一些常见的方法。
  • Vue3中如何实现单页应用(SPA)导航操作
  • HTML中的块元素与行内元素
  • P8700 [蓝桥杯 2019 国 B] 解谜游戏--string与cstring、memset()介绍
  • Unity Job系统详解原理和基础应用处理大量物体位置
  • 24.Harmonyos Next仿uv-ui 组件 NumberBox 步进器组件步长设置
  • Android GMS集成
  • pytorch下载速度慢?试试离线安装
  • Yashan DB 实例管理
  • 蓝桥备赛(12)- 顺序表和 vector(上)
  • 《C#上位机开发从门外到门内》2-1:串口通信(UART)
  • 【linux】【文件】文件权限基础
  • 03 2个路由器构造三个子网相互访问, 3个路由器构造5个子网相互访问
  • PDF处理控件Aspose.PDF,如何实现企业级PDF处理
  • 测试大语言模型在嵌入式设备部署的可能性-ollama本地部署测试