# SpringBoot如何整合OpenApi
## 目錄
1. [OpenAPI與Swagger簡介](#1-openapi與swagger簡介)
2. [SpringBoot集成OpenAPI的三種方式](#2-springboot集成openapi的三種方式)
3. [基于SpringDoc的完整整合方案](#3-基于springdoc的完整整合方案)
4. [OpenAPI規范的高級配置](#4-openapi規范的高級配置)
5. [接口安全與權限控制](#5-接口安全與權限控制)
6. [生產環境最佳實踐](#6-生產環境最佳實踐)
7. [常見問題解決方案](#7-常見問題解決方案)
---
## 1. OpenAPI與Swagger簡介
### 1.1 什么是OpenAPI規范
OpenAPI規范(前身Swagger規范)是RESTful API設計的行業標準,通過YAML或JSON格式描述API的:
- 端點(Endpoints)
- 操作(HTTP方法)
- 參數(查詢/路徑/請求體)
- 返回格式
- 認證方式
```yaml
# 示例:OpenAPI 3.0定義
openapi: 3.0.3
info:
title: 用戶服務API
version: 1.0.0
paths:
/users:
get:
summary: 獲取用戶列表
responses:
'200':
description: 成功返回用戶數組
自SpringFox 3.0停止維護后,主流方案遷移至: - SpringDoc OpenAPI(推薦) - Swagger Core原生集成
方案 | 優點 | 缺點 |
---|---|---|
SpringFox | 歷史項目兼容性好 | 已停止維護 |
SpringDoc | 活躍維護,支持OpenAPI 3.1 | 需要JDK11+ |
手動編寫YAML | 完全控制規范內容 | 維護成本高 |
<!-- pom.xml示例 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
SpringDoc通過掃描以下Spring注解自動構建OpenAPI模型:
- @RestController
- @RequestMapping
- @Operation
(Swagger注解)
- @Parameter
@Configuration
@OpenAPIDefinition(
info = @Info(
title = "電商平臺API",
version = "v1.0",
contact = @Contact(name = "Dev Team", email = "dev@example.com")
)
)
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.components(new Components()
.addSecuritySchemes("bearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")))
.addSecurityItem(
new SecurityRequirement().addList("bearerAuth"));
}
}
@RestController
@RequestMapping("/api/products")
@Tag(name = "商品管理", description = "商品CRUD操作")
public class ProductController {
@Operation(summary = "獲取商品詳情",
parameters = @Parameter(name = "id", description = "商品ID"))
@ApiResponse(responseCode = "404", description = "商品不存在")
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
// 實現邏輯
}
}
@Schema(description = "商品數據模型")
public class Product {
@Schema(description = "商品唯一ID", example = "1001")
private Long id;
@Schema(description = "商品名稱", requiredMode = REQUIRED)
private String name;
}
@Bean
@GroupedOpenApi
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("admin")
.pathsToMatch("/admin/**")
.build();
}
@Operation(responses = {
@ApiResponse(
responseCode = "200",
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
value = "{\"code\":200,\"data\":{\"name\":\"示例商品\"}}"
)
)
)
})
# application-prod.yml
springdoc:
swagger-ui:
enabled: false
api-docs:
enabled: false
.securitySchemes(List.of(
new SecurityScheme()
.name("Authorization")
.type(HTTP)
.scheme("bearer")
.bearerFormat("JWT")
))
@Hidden // 隱藏接口
@PreAuthorize("hasRole('ADMIN')")
public void deleteProduct() {}
springdoc.cache.disabled=false
springdoc.packagesToScan=com.example.api
@Bean
public OpenApiCustomiser addSecurityHeaders() {
return openApi -> openApi.getPaths().values()
.forEach(pathItem -> pathItem.readOperations()
.forEach(operation ->
operation.addParametersItem(new HeaderParameter()
.required(false)
.name("X-Request-ID"))));
}
springdoc:
cors:
enabled: true
paths: /**
@Schema(type = "string", allowableValues = {"A","B","C"})
private StatusEnum status;
@Operation(requestBody = @RequestBody(
content = @Content(mediaType = "multipart/form-data",
schema = @Schema(type = "object"),
encoding = @Encoding(name = "file", contentType = "application/octet-stream"))
)
最佳實踐總結:建議采用SpringDoc作為主要集成方案,配合注解驅動開發,同時通過
@Profile
控制生產環境文檔暴露。完整示例代碼可參考GitHub示例倉庫 “`
(注:此為精簡版框架,完整5100字版本需擴展每個章節的詳細實現步驟、原理圖解、性能對比數據等內容)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。