Java案例怎么整合Swagger文档?

wen java案例 53

本文目录导读:

Java案例怎么整合Swagger文档?

  1. 为什么选择 SpringDoc?
  2. 整合步骤(Spring Boot 3.x + SpringDoc)
  3. 常用配置(application.yml)
  4. 生产环境安全控制(重要)
  5. 常见问题与解决
  6. 汇总:最佳实践建议

整合Swagger文档到Java项目(通常使用Spring Boot)可以极大提升前后端协作效率,让API接口文档自动生成并支持在线调试。

目前最主流的方式是使用 SpringDoc OpenAPI(推荐)或 Springfox(已停止维护),以下是基于 SpringDoc 的详细整合步骤及最佳实践。


为什么选择 SpringDoc?

  • 官方推荐:与 Spring Boot 3.x / Spring 6.x 完美兼容,支持 jakarta 命名空间。
  • 性能更好:基于 OpenAPI 3.0 规范,启动速度更快。
  • 活跃维护:相比 Springfox(停更于 2020年),SpringDoc 至今仍在更新。

整合步骤(Spring Boot 3.x + SpringDoc)

引入 Maven 依赖

pom.xml 中添加:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.6.0</version> <!-- 请使用最新版 -->
</dependency>
  • WebFlux 项目:将 webmvc 改为 webflux

配置 OpenAPI 信息(可选但推荐)

创建配置类,定义文档标题、版本、联系人等元数据。

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPIConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("XX系统 API文档")
                        .version("1.0")
                        .description("这是一个示例API接口文档")
                        .contact(new Contact()
                                .name("开发者")
                                .email("dev@example.com")
                        )
                );
    }
}

在 Controller 和实体类中添加注解(核心)

使用 Swagger 注解描述接口细节。

Controller 层示例:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户增删改查接口")  // 分组标签
public class UserController {
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询用户", description = "通过用户ID获取详细信息")
    public User getUser(@PathVariable Long id) {
        // ...
    }
    @PostMapping
    @Operation(summary = "创建新用户")
    public User createUser(@RequestBody @Valid User user) {
        // ...
    }
}

实体类/DTO 示例:

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "用户实体")  // 描述模型
public class User {
    @Schema(description = "用户ID", example = "1")
    private Long id;
    @Schema(description = "用户名", requiredMode = Schema.RequiredMode.REQUIRED, example = "张三")
    private String username;
    @Schema(description = "邮箱", example = "zhang@example.com")
    private String email;
}

访问 Swagger UI

启动项目后,访问以下地址:

  • Swagger UIhttp://localhost:8080/swagger-ui.html
  • OpenAPI JSONhttp://localhost:8080/v3/api-docs

常用配置(application.yml)

application.yml 中进行更精细的控制:

springdoc:
  api-docs:
    path: /v3/api-docs # JSON文档路径,默认即此
  swagger-ui:
    path: /swagger-ui.html # UI页面路径
    enabled: true # 生产环境建议设为false
    try-it-out-enabled: true # 是否启用“Try it out”调试按钮
  packages-to-scan: com.example.controller # 扫描指定包(可选,默认全局扫描)
  paths-to-match: /api/** # 只扫描匹配路径的接口

生产环境安全控制(重要)

Swagger UI 在开发/测试环境很方便,但上线前必须禁用,否则会暴露所有接口。

方法1:通过 Profile 控制

# application-dev.yml
springdoc:
  swagger-ui:
    enabled: true
# application-prod.yml
springdoc:
  swagger-ui:
    enabled: false

方法2:配置类+条件注解

@Configuration
@Profile("dev")  // 仅在dev环境生效
public class SwaggerConfig {
    // ...
}

常见问题与解决

问题 原因及解决
404 无法访问 Swagger UI 未添加依赖;
Spring Boot 版本与 SpringDoc 版本不匹配(需用 2.x for Boot 3.x);
配置了 paths-to-match 但未包含 /swagger-ui
接口文档中参数类型不对 未在实体类的字段上添加 @Schema(example=...),或用 @RequestParam 时缺少注解。
分组显示混乱 在 Controller 上使用 @Tag(name="组名") 统一管理。
生产环境忘记关闭 配置 springdoc.swagger-ui.enabled=false 或使用 @Profile

汇总:最佳实践建议

  1. 使用 SpringDoc(而不是 Springfox)作为依赖。
  2. 统一描述:团队内约定好 @Schema@Operation 的使用规范。
  3. 版本控制:在 OpenAPI 配置中维护好版本号,与后端发布版本同步。
  4. 自动生成:可借助 Knife4j(基于 SpringDoc 的增强 UI)获得更美观的界面。
    • 依赖:com.github.xiaoymin:knife4j-openapi3-jakarta-spring-boot-starter
    • 访问路径:/doc.html

通过以上步骤,你就能快速在 Java 项目中整合一套自动更新、可在线调试的 Swagger 文档了。

抱歉,评论功能暂时关闭!