springdoc-openapi Java 庫有助于使用 Spring Boot 項目自動生成 API 文檔。springdoc-openapi 通過在運行時檢查應用程序來根據 Spring 配置、類結構和各種注釋推斷 API 語義。
該庫會自動生成 JSON/YAML 和 HTML 格式的頁面文檔。生成的文檔可以使用swagger-api注釋進行補充。
github地址 官網
1. 項目依賴版本
- Spring-Boot: 3.1.0
2. 引入依賴
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.3.0</version></dependency>
3. 配置
package com.omni.admin.swagger;import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** SpringDoc配置**/
@Configuration
@ConditionalOnExpression("${springdoc.api-docs.enabled:true}")
public class SwaggerDocConfig {@Resourceprivate SwaggerDocProperties springDocProperties;@Beanpublic OpenAPI openAPI() {return new OpenAPI().info(new Info().title(springDocProperties.getTitle()).version(springDocProperties.getApplicationVersion())).addSecurityItem(new SecurityRequirement().addList(springDocProperties.getTokenName())).components(new Components().addSecuritySchemes(springDocProperties.getTokenName(),getSecurityScheme()));}private SecurityScheme getSecurityScheme(){return new SecurityScheme().name(springDocProperties.getTokenName()).in(SecurityScheme.In.HEADER).type(SecurityScheme.Type.APIKEY).scheme("basic");}
}
package com.omni.admin.swagger;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;import java.util.List;/*** swagger配置類**/
@Data
@Configuration
@ConfigurationProperties(prefix = "springdoc")
@ConditionalOnExpression("${springdoc.api-docs.enabled:true}")
public class SwaggerDocProperties {/*** 項目應用名*/@Value("${spring.application.name:接口文檔}")private String applicationName;/*** 項目名稱*/private String title = "Omni-Admin后臺管理系統接口文檔";/*** 項目版本信息*/private String applicationVersion = "1.0.0";/*** 項目描述信息*/private String applicationDescription;/*** 認證token的名稱*/private String tokenName = "X-Access-Token";/*** 文檔組配置*/private List<Group> groups;@Datapublic static class Group{private String modelName;/*** 組名稱*/private String name;/*** 組所屬的包*/private String packageName;}
}
4. properties配置
這里需要做一些說明:其中配置了排序相關和分模塊。還有默認訪問是全部文檔是展開的,可以配置默認合并。
# springdoc接口文檔配置 配置參考 springdoc.md
springdoc.api-docs.enabled=true
springdoc.swagger-ui.tags-sorter=alpha
springdoc.swagger-ui.operations-sorter=method
springdoc.group-configs[0].group=A-平臺管理
springdoc.group-configs[0].packages-to-scan[0]=auth.platform.service.platform
springdoc.group-configs[1].group=B-標簽管理
springdoc.group-configs[1].packages-to-scan[0]=auth.platform.service.tag
springdoc.group-configs[2].group=C-配置中心
springdoc.group-configs[2].packages-to-scan[0]=auth.platform.service.configcenter
springdoc.group-configs[3].group=D-日志管理
springdoc.group-configs[3].packages-to-scan[0]=auth.platform.service.log
springdoc.group-configs[4].group=F-監控管理
springdoc.group-configs[4].packages-to-scan[0]=auth.platform.service.monitor
springdoc.group-configs[5].group=G-文件管理
springdoc.group-configs[5].packages-to-scan[0]=auth.platform.service.file
springdoc.group-configs[6].group=H-WS消息管理
springdoc.group-configs[6].packages-to-scan[0]=auth.platform.service.websocket
# 該配置控制是否需要在界面顯示過濾框
springdoc.swagger-ui.filter=true
# 該配置主要控制swagger顯示是直接展開還是關閉 none 不默認展開 list 列出所有api full直接展開所有api
springdoc.swagger-ui.doc-expansion=none
5. 訪問
http://localhost:8080/swagger-ui/index.html
6. Controller示例
package com.omni.admin.controller;import com.omni.admin.common.result.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** 接口信息表*/
@Tag(name = "接口管理")
@RestController
@RequestMapping("/api-info")
public class ApiInfoController {@Operation(summary = "測試接口文檔")@GetMapping("/demo")public ApiResult<Void> demo(){return ApiResult.success();}}
7. Springdoc-openapi 屬性
springdoc-openapi依賴于使用標準文件位置的標準 Spring 配置屬性(YML 或屬性)。
7.1. Springdoc-OpenAPI 核心屬性
參數名稱 | 默認值 | 描述 |
---|---|---|
springdoc.api-docs.path | /v3/api-docs | String ,用于 Json 格式的 OpenAPI 文檔的自定義路徑。 |
springdoc.api-docs.enabled | true | Boolean .禁用 springdoc-openapi 端點(默認為 /v3/api-docs)。 |
springdoc.packages-to-scan | * | List of Strings .要掃描的包列表(逗號分隔) |
springdoc.paths-to-match | /* | List of Strings .要匹配的路徑列表(逗號分隔) |
springdoc.produces-to-match-to | /* | List of Strings .生成要匹配的媒體類型列表(逗號分隔) |
springdoc.headers-to-match | /* | List of Strings .要匹配的標頭列表(逗號分隔) |
springdoc.consumptions-to-matchs. | /* | List of Strings .要匹配的消耗媒體類型列表(逗號分隔) |
springdoc.paths-to-exclude | List of Strings .要排除的路徑列表(逗號分隔) | |
springdoc.packages-to-exclude | List of Strings .要排除的包列表(逗號分隔) | |
springdoc.default-consumptions-media-type | application/json | String .默認使用媒體類型。 |
springdoc.default-produces-media-type | **/** | String .默認生成媒體類型。 |
springdoc.cache.disabled | false | Boolean .禁用計算的 OpenAPI 的 springdoc-openapi 緩存。 |
彈簧文檔顯示執行器 | false | Boolean .顯示執行器端點。 |
springdoc.auto-tag-classes | true | Boolean .禁用 springdoc-openapi 自動標記。 |
springdoc.model-and-view-allow | false | Boolean .允許帶有 ModelAndView 的 RestControllers 返回出現在 OpenAPI 描述中。 |
springdoc.override-with-generic-response | true | Boolean .如果為 true,則自動將@ControllerAdvice響應添加到所有生成的響應中。 |
springdoc.api-docs.groups.enabled | true | Boolean .禁用 springdoc-openapi 組。 |
springdoc.group-configs[0].group | String .組名稱 | |
springdoc.group-configs[0].displayName | String .組的顯示名稱。 | |
springdoc.group-configs[0].packages-to-scan | * | List of Strings .要掃描組的包列表(逗號分隔) |
springdoc.group-configs[0].paths-to-match | /* | List of Strings .要為組匹配的路徑列表(逗號分隔) |
springdoc.group-configs[0].paths-to-exclude | `` | List of Strings .要為組排除的路徑列表(逗號分隔) |
springdoc.group-configs[0].packages-to-exclude | List of Strings .要為組排除的包列表(逗號分隔) | |
springdoc.group-configs[0].produces-to-match | /* | List of Strings .生成要匹配的媒體類型列表(逗號分隔) |
springdoc.group-configs[0].consumes-to-match | /* | List of Strings .要匹配的消耗媒體類型列表(逗號分隔) |
springdoc.group-configs[0].headers-to-match | /* | List of Strings .要匹配的標頭列表(逗號分隔) |
springdoc.webjars.prefix | /webjars | String ,要更改 webjars 前綴,該前綴可見 swagger-ui 的 URL 為 spring-webflux。 |
springdoc.api-docs.resolve-schema-properties | false | Boolean .在@Schema(名稱、標題和說明)上啟用屬性解析程序。 |
springdoc.remove-broken-reference-definition | true | Boolean .禁用刪除損壞的引用定義。 |
springdoc.writer-with-default-pretty-printer | false | Boolean .啟用OpenApi規范的漂亮打印。 |
springdoc.model-converters.deprecating-converter.enabled | true | Boolean .禁用棄用模型轉換器。 |
springdoc.model-converters.polymorphic-converter.enabled | true | Boolean .禁用多態模型轉換器。 |
springdoc.model-converters.pageable-converter.enabled | true | Boolean .禁用可分頁模型轉換器。 |
springdoc.model-converters.sort-converter.enabled | true | Boolean .禁用排序轉換器。 |
springdoc.use-fqn | false | Boolean .啟用完全限定名稱。 |
springdoc.show-login-endpoint | false | Boolean .使 Spring 安全登錄端點可見。 |
springdoc.pre-load-enabled | false | Boolean .預加載設置,用于在應用程序啟動時加載 OpenAPI。 |
springdoc.writer-with-order-by-keys | false | Boolean .啟用確定性/字母順序排序。 |
springdoc.use-management-port | false | Boolean .在執行器管理端口上公開招搖 UI。 |
springdoc.disable-i18n | false | Boolean .使用 i18n 禁用自動翻譯。 |
springdoc.show-spring-cloud-functions | true | Boolean .顯示彈簧云函數 Web 終結點。 |
springdoc.api-docs.version | openapi_3_0 | String .選擇或(使用值 )。OpenAPI 3.0``OpenAPI 3.1``OPENAPI_3_1 |
springdoc.default-flat-paramObject | false | Boolean .默認平展參數。 |
springdoc.default-support-form-data | false | Boolean .在指定 api 以接受表單數據時默認設置表單數據的參數。 |
7.2. swagger-ui 屬性
- 上提供了對 swagger-ui 屬性的支持。請參閱官方文檔。
springdoc-openapi
- 您可以在文檔中使用與 Spring 引導屬性相同的 swagger-ui 屬性。
參數名稱 | 默認值 | 描述 |
---|---|---|
springdoc.swagger-ui.path | /swagger-ui.html | String ,用于 swagger-ui HTML 文檔的自定義路徑。 |
springdoc.swagger-ui.enabled | true | Boolean .禁用 swagger-ui 端點(默認情況下為 /swagger-ui.html)。 |
springdoc.swagger-ui.configUrl | /v3/api-docs/swagger-config | String .要從中獲取外部配置文檔的 URL。 |
springdoc.swagger-ui.layout | BaseLayout | String .通過插件系統提供的組件的名稱,用作 Swagger UI 的頂級布局。 |
springdoc.swagger-ui.validatorUrl | validator.swagger.io/validator | 默認情況下,Swagger UI 會嘗試根據 swagger.io 的在線驗證器驗證規范。您可以使用此參數設置不同的驗證程序 URL,例如,對于本地部署的驗證程序驗證程序徽章。將其設置為 ,或者將禁用驗證。none``127.0.0.1``localhost |
springdoc.swagger-ui.tryItOutEnabled | false | Boolean .控制默認情況下是否應啟用“試用”部分。 |
springdoc.swagger-ui.filter | false | Boolean OR String .如果設置,則啟用篩選。頂部欄將顯示一個編輯框,可用于篩選顯示的標記操作。可以是用于啟用或禁用的布爾值,也可以是字符串,在這種情況下,將使用該字符串作為篩選器表達式啟用篩選。篩選區分大小寫,與標記內任意位置的篩選器表達式匹配。 |
springdoc.swagger-ui.operationsSorter | Function=(a ? a) .對每個 API 的操作列表應用排序。它可以是“alpha”(按路徑字母數字排序),“method”(按HTTP方法排序)或函數(參見Array.prototype.sort()以了解排序函數的工作原理)。默認值為服務器返回的順序不變。 | |
springdoc.swagger-ui.tagsSorter | Function=(a ? a) .對每個 API 的標記列表應用排序。它可以是“alpha”(按路徑字母數字排序)或函數,請參閱 Array.prototype.sort() 以學習如何編寫排序函數)。每次傳遞時,將兩個標記名稱字符串傳遞給分揀機。默認值是由 Swagger UI 確定的順序。 | |
springdoc.swagger-ui.oauth2RedirectUrl | /swagger-ui/oauth2-redirect.html | String .OAuth 重定向網址。 |
springdoc.swagger-ui.displayOperationId | false | Boolean .控制操作 ID 在操作列表中的顯示。缺省值為 。false |
springdoc.swagger-ui.displayRequestDuration | false | Boolean .控制“試用”請求的請求持續時間(以毫秒為單位)的顯示。 |
springdoc.swagger-ui.deepLink | false | Boolean .如果設置為 ,則啟用標簽和操作的深層鏈接。有關更多信息,請參閱 [深層鏈接文檔](/docs/usage/deep-linking.md)。true |
springdoc.swagger-ui.defaultModelsExpandDepth | 1 | Number .模型的默認擴展深度(設置為 -1 將完全隱藏模型)。 |
springdoc.swagger-ui.defaultModelExpandDepth | 1 | Number .模型示例部分上模型的默認擴展深度。 |
springdoc.swagger-ui.defaultModelRendering | String=["example"*, "model"] .控制首次呈現 API 時模型的顯示方式。(用戶始終可以通過單擊“模型”和“示例值”鏈接來切換給定模型的渲染。 | |
springdoc.swagger-ui.docExpansion | String=["list"*, "full", "none"] .控制操作和標記的默認展開設置。它可以是“列表”(僅展開標簽)、“完整”(展開標簽和操作)或“無”(不展開任何內容)。 | |
springdoc.swagger-ui.maxDisplayTags | Number .如果設置,將顯示的標記操作數限制為最多此數量。默認值為顯示所有操作。 | |
springdoc.swagger-ui.showExtensions | false | Boolean .控制供應商擴展 () 字段和操作、參數和架構的值的顯示。x- |
springdoc.swagger-ui.url | String .要配置,自定義 OpenAPI 文件的路徑。如果使用,將被忽略。urls | |
springdoc.swagger-ui.showCommonExtensions | false | Boolean .控制參數的擴展 (、、、、) 字段和值的顯示。pattern``maxLength``minLength``maximum``minimum |
springdoc.swagger-ui.supportedSubmitMethods | Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"] .啟用了“試用”功能的 HTTP 方法列表。空數組禁用所有操作的“試用”。這不會從顯示中過濾操作。 | |
springdoc.swagger-ui.queryConfigEnabled | false | Boolean .自 以來禁用。此參數啟用(舊版)通過 URL 搜索參數覆蓋配置參數。在啟用此功能之前,請參閱安全公告。v1.6.0 |
springdoc.swagger-ui.oauth. additionalQueryStringParams | String .添加到授權 URL 和令牌 URL 的其他查詢參數。 | |
springdoc.swagger-ui.disable-swagger-default-url | false | Boolean .禁用 swagger-ui 默認寵物商店網址。(從 v1.4.1 開始可用)。 |
springdoc.swagger-ui.urls[0].url | URL .Topbar 插件使用的 swagger 組的 url。URL 在此數組中的所有項中必須是唯一的,因為它們用作標識符。 | |
springdoc.swagger-ui.urls[0].name | String .Topbar 插件使用的 swagger 組的名稱。名稱在此數組中的所有項中必須是唯一的,因為它們用作標識符。 | |
springdoc.swagger-ui.urlsPrimaryName | String .加載 Swagger UI 時將顯示的招搖組的名稱。 | |
springdoc.swagger-ui.oauth.clientId | String .默認客戶端 ID。必須是字符串。 | |
springdoc.swagger-ui.oauth.clientSecret | String .默認客戶端機密。切勿在生產環境中使用此參數。它公開了重要的安全信息。此功能僅適用于開發/測試環境。 | |
springdoc.swagger-ui.oauth.realm | String .領域查詢參數(適用于 OAuth 1)已添加到授權 URL 和令牌 URL。 | |
springdoc.swagger-ui.oauth.appName | String .OAuth 應用程序名稱,顯示在授權彈出窗口中。 | |
springdoc.swagger-ui.oauth.scopeSeparator | String .用于傳遞范圍的 OAuth 范圍分隔符,在調用之前進行編碼,默認值為空格(編碼值 %20)。 | |
springdoc.swagger-ui.csrf.enabled | false | Boolean .啟用 CSRF 支持 |
springdoc.swagger-ui.csrf.use-local-storage | false | Boolean .從本地存儲獲取 CSRF 令牌。 |
springdoc.swagger-ui.csrf.use-session-storage | false | Boolean .從會話存儲中獲取 CSRF 令牌。 |
springdoc.swagger-ui.csrf.cookie-name | XSRF-TOKEN | String .可選的 CSRF,用于設置 CSRF cookie 名稱。 |
springdoc.swagger-ui.csrf.header-name | X-XSRF-TOKEN | String .可選的 CSRF,用于設置 CSRF 標頭名稱。 |
springdoc.swagger-ui.syntaxHighlight.activated | true | Boolean .是否應激活語法突出顯示。 |
springdoc.swagger-ui.syntaxHighlight.theme | agate | String …突出顯示.js要使用的語法著色主題。(只有這 6 種樣式可用。String=["agate"*, "arta", "monokai", "nord", "obsidian", "tomorrow-night"] |
springdoc.swagger-ui.oauth. useBasicAuthentication WithAccessCodeGrant | false | Boolean .僅針對訪問代碼流激活。在對 tokenURL 的authorization_code請求期間,使用 HTTP 基本身份驗證方案(具有基本 base64encode(client_id + client_secret)的授權標頭)傳遞客戶端密碼。 |
springdoc.swagger-ui.oauth. usePkceWithAuthorization CodeGrant | false | Boolean .僅適用于授權代碼流。代碼交換的證明密鑰為 OAuth 公共客戶端帶來了增強的安全性。 |
springdoc.swagger-ui.persistAuthorization | false | Boolean .如果設置為 true,它將保留授權數據,并且在瀏覽器關閉/刷新時不會丟失 |
springdoc.swagger-ui.use-root-path | false | Boolean .如果設置為 true,則可以直接從應用程序根路徑訪問 swagger-u。 |
8. Springdoc-openapi 實例
8.1. springdoc 應用實例
8.2 演示應用程序的源代碼
https://github.com/springdoc/springdoc-openapi-demos.git
9. 從SpringFox遷移
- 刪除 springfox 和 swagger 2 依賴項。改為添加依賴項。
springdoc-openapi-ui
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.14</version> </dependency>
- 將 swagger 2 注釋替換為 swagger 3 注釋(它已包含在依賴項中)。 招搖 3 注釋的包是 .
springdoc-openapi-ui``io.swagger.v3.oas.annotations
@Api
→@Tag
@ApiIgnore
→或或@Parameter(hidden = true)``@Operation(hidden = true)``@Hidden
@ApiImplicitParam
→@Parameter
@ApiImplicitParams
→@Parameters
@ApiModel
→@Schema
@ApiModelProperty(hidden = true)
→@Schema(accessMode = READ_ONLY)
@ApiModelProperty
→@Schema
@ApiOperation(value = "foo", notes = "bar")
→@Operation(summary = "foo", description = "bar")
@ApiParam
→@Parameter
@ApiResponse(code = 404, message = "foo")
→@ApiResponse(responseCode = "404", description = "foo")
- 如果使用對象捕獲多個請求查詢參數,請使用
@ParameterObject
- 此步驟是可選的:僅當您有多個 bean 時,才將它們替換為 bean。
Docket``GroupedOpenApi
以前:
@Bean public Docket publicApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.public")) .paths(PathSelectors.regex("/public.*")) .build() .groupName("springshop-public") .apiInfo(apiInfo()); } @Bean public Docket adminApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.admin")) .paths(PathSelectors.regex("/admin.*")) .apis(RequestHandlerSelectors.withMethodAnnotation(Admin.class)) .build() .groupName("springshop-admin") .apiInfo(apiInfo()); }
現在:
@Bean public GroupedOpenApi publicApi() { return GroupedOpenApi.builder() .group("springshop-public") .pathsToMatch("/public/**") .build(); } @Bean public GroupedOpenApi adminApi() { return GroupedOpenApi.builder() .group("springshop-admin") .pathsToMatch("/admin/**") .addMethodFilter(method -> method.isAnnotationPresent(Admin.class)) .build(); }
如果你只有一個 - 刪除它,而是將屬性添加到你的 :Docket``application.properties
springdoc.packagesToScan=package1, package2
springdoc.pathsToMatch=/v1, /api/balance/**
@Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title("SpringShop API") .description("Spring shop sample application") .version("v0.0.1") .license(new License().name("Apache 2.0").url("http://springdoc.org"))) .externalDocs(new ExternalDocumentation() .description("SpringShop Wiki Documentation") .url("https://springshop.wiki.github.org/docs")); }