Skip to content
清晨的一缕阳光
返回

Spring Boot OpenAPI 3.0 文档

前言

API 文档是 RESTful API 开发中不可或缺的一部分。OpenAPI 3.0 是目前最流行的 API 规范。Spring Boot 通过 springdoc-openapi 可以轻松生成 OpenAPI 3.0 文档。

快速开始

1. 添加依赖

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>

2. 基础配置

springdoc:
  api-docs:
    path: /v3/api-docs
    enabled: true
  swagger-ui:
    path: /swagger-ui.html
    enabled: true
    display-request-duration: true
    operations-sorter: alpha
    tags-sorter: alpha
  packages-to-scan: com.example.demo.controller
  paths-to-match: /api/**

3. 访问文档

基础注解

1. @Operation 接口描述

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {
    
    @Operation(summary = "获取用户列表", description = "分页获取用户列表")
    @GetMapping
    public R<List<UserDTO>> getUsers(
        @Parameter(description = "页码", example = "1") @RequestParam int page,
        @Parameter(description = "每页大小", example = "10") @RequestParam int size
    ) {
        return R.ok(userService.findAll(page, size));
    }
    
    @Operation(summary = "获取用户详情", description = "根据 ID 获取用户详情")
    @GetMapping("/{id}")
    public R<UserDTO> getUser(
        @Parameter(description = "用户 ID", example = "1") @PathVariable Long id
    ) {
        return R.ok(userService.findById(id));
    }
    
    @Operation(summary = "创建用户", description = "创建新用户")
    @PostMapping
    public R<UserDTO> create(
        @RequestBody UserDTO dto
    ) {
        return R.ok(userService.create(dto));
    }
}

2. @ApiResponse 响应描述

@Operation(summary = "获取用户详情")
@ApiResponses({
    @ApiResponse(responseCode = "200", description = "成功",
        content = @Content(schema = @Schema(implementation = UserDTO.class))
    ),
    @ApiResponse(responseCode = "404", description = "用户不存在"),
    @ApiResponse(responseCode = "500", description = "服务器内部错误")
})
@GetMapping("/{id}")
public R<UserDTO> getUser(@PathVariable Long id) {
    return R.ok(userService.findById(id));
}

3. @Schema 模型描述

@Data
@Schema(description = "用户信息")
public class UserDTO {
    
    @Schema(description = "用户 ID", example = "1", accessMode = Schema.AccessMode.READ_ONLY)
    private Long id;
    
    @Schema(description = "用户名", example = "zhangsan", required = true)
    private String username;
    
    @Schema(description = "邮箱", example = "zhangsan@example.com", required = true)
    private String email;
    
    @Schema(description = "创建时间", example = "2024-01-01 12:00:00", accessMode = Schema.AccessMode.READ_ONLY)
    private LocalDateTime createdAt;
    
    @Schema(description = "用户状态", example = "ACTIVE", allowableValues = {"ACTIVE", "INACTIVE"})
    private UserStatus status;
}

@Schema(description = "用户状态")
public enum UserStatus {
    @Schema(description = "启用") ACTIVE,
    @Schema(description = "禁用") INACTIVE
}

分组配置

1. 多分组配置

springdoc:
  group-configs:
    - group: 用户模块
      paths-to-match: /api/users/**
      packages-to-scan: com.example.demo.controller.user
    - group: 订单模块
      paths-to-match: /api/orders/**
      packages-to-scan: com.example.demo.controller.order

2. 使用@Group

@RestController
@RequestMapping("/api/users")
@Group(name = "用户模块")
public class UserController {
    // ...
}

@RestController
@RequestMapping("/api/orders")
@Group(name = "订单模块")
public class OrderController {
    // ...
}

访问:

认证配置

1. JWT 认证

@Configuration
public class OpenApiConfig {
    
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("Demo API")
                .version("1.0")
                .description("Spring Boot 4 Demo API 文档")
            )
            .addSecurityItem(new SecurityRequirement().addList("Bearer Authentication"))
            .components(new Components()
                .addSecuritySchemes("Bearer Authentication", createAPIKeyScheme())
            );
    }
    
    private SecurityScheme createAPIKeyScheme() {
        return new SecurityScheme()
            .type(SecurityScheme.Type.HTTP)
            .bearerFormat("JWT")
            .scheme("bearer");
    }
}

2. 使用认证

@Operation(summary = "获取用户详情")
@SecurityRequirement(name = "Bearer Authentication")
@GetMapping("/{id}")
public R<UserDTO> getUser(@PathVariable Long id) {
    return R.ok(userService.findById(id));
}

自定义 UI

1. 自定义 CSS

springdoc:
  swagger-ui:
    custom-css: "/css/custom-swagger.css"
/* /static/css/custom-swagger.css */
.swagger-ui .topbar {
    background-color: #1890ff;
}

.swagger-ui .info .title {
    color: #1890ff;
}

2. 自定义 JS

springdoc:
  swagger-ui:
    custom-js: "/js/custom-swagger.js"

3. 禁用 Swagger UI

springdoc:
  swagger-ui:
    enabled: false

请求示例

1. 示例值

@Schema(description = "创建用户请求")
@Data
public class UserCreateDTO {
    
    @Schema(description = "用户名", example = "zhangsan")
    private String username;
    
    @Schema(description = "邮箱", example = "zhangsan@example.com")
    private String email;
    
    @Schema(description = "年龄", example = "25")
    private Integer age;
}

2. 示例对象

@Operation(summary = "创建用户")
@RequestBody(
    description = "用户信息",
    required = true,
    content = @Content(
        schema = @Schema(implementation = UserCreateDTO.class),
        examples = {
            @ExampleObject(
                name = "普通用户",
                value = "{\"username\": \"zhangsan\", \"email\": \"zhangsan@example.com\", \"age\": 25}"
            ),
            @ExampleObject(
                name = "管理员",
                value = "{\"username\": \"admin\", \"email\": \"admin@example.com\", \"age\": 30}"
            )
        }
    )
)
@PostMapping
public R<UserDTO> create(@RequestBody UserCreateDTO dto) {
    return R.ok(userService.create(dto));
}

文件上传

@Operation(summary = "上传头像")
@PostMapping("/avatar")
public R<String> uploadAvatar(
    @Parameter(description = "头像文件")
    @RequestParam("file") MultipartFile file
) {
    String url = fileService.upload(file);
    return R.ok(url);
}

最佳实践

1. 统一响应格式

@Schema(description = "统一响应")
@Data
public class R<T> {
    
    @Schema(description = "状态码", example = "200")
    private int code;
    
    @Schema(description = "消息", example = "success")
    private String message;
    
    @Schema(description = "数据")
    private T data;
    
    @Schema(description = "时间戳", example = "2024-01-01 12:00:00")
    private LocalDateTime timestamp;
}

2. 分页响应

@Schema(description = "分页响应")
@Data
public class PageResult<T> {
    
    @Schema(description = "数据列表")
    private List<T> list;
    
    @Schema(description = "总数", example = "100")
    private long total;
    
    @Schema(description = "页码", example = "1")
    private int page;
    
    @Schema(description = "每页大小", example = "10")
    private int size;
    
    @Schema(description = "总页数", example = "10")
    private int pages;
}

3. 生产环境配置

# application-prod.yml
springdoc:
  api-docs:
    enabled: false  # 生产环境禁用
  swagger-ui:
    enabled: false  # 生产环境禁用

4. 使用 Profile

@Configuration
@Profile("!prod")
public class OpenApiConfig {
    
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("Demo API")
                .version("1.0")
            );
    }
}

总结

OpenAPI 文档要点:

良好的 API 文档,能提升开发效率和用户体验。


分享这篇文章到:

上一篇文章
Java 字节码基础
下一篇文章
Nacos 高可用部署