SpringBoot集成Swagger

https://blog.csdn.net/qq_27890899/article/details/131780613
SpringFox:https://springfox.github.io/springfox/
1OpenAPI規(guī)范
1.1介紹
OpenAPI規(guī)范(OAS)定義了一個標(biāo)準(zhǔn)的、與語言無關(guān)的HTTP api接口,它允許人類和計算機(jī)發(fā)現(xiàn)和理解服務(wù)的功能,而無需訪問源代碼、文檔或通過網(wǎng)絡(luò)流量檢查。正確定義后,使用者可以用最少的實現(xiàn)邏輯理解遠(yuǎn)程服務(wù)并與之交互。
OpenAPI3.1.0規(guī)范詳情請參閱Swagger官網(wǎng):https://swagger.io/specification/
1.2OAS與Swagger關(guān)系
Swagger 和 OpenAPI 實際上是密切相關(guān)的概念。Swagger 是一種用于設(shè)計、構(gòu)建、文檔化和消費 RESTful API 的工具集,而 OpenAPI 是 Swagger 的規(guī)范化版本。
具體來說,OpenAPI Specification(OAS)是一個基于 JSON 或 YAML 格式的文檔規(guī)范,用于描述和定義 API 的結(jié)構(gòu)、操作、參數(shù)、響應(yīng)等。它提供了一種標(biāo)準(zhǔn)化的方式,使得不同的開發(fā)團(tuán)隊可以理解和交流關(guān)于 API 的信息。
Swagger 以前是由 SmartBear Software 開發(fā)并維護(hù)的一組工具和開源項目,包括 Swagger UI、Swagger Editor 等。然而,在 Swagger 規(guī)范化之后,Swagger 社區(qū)和規(guī)范正式改名為 OpenAPI。因此,Swagger 和 OpenAPI 實際上是同一個東西,只是 Swagger 是之前版本的稱呼,而 OpenAPI 是 Swagger 規(guī)范化后的稱呼。
2Springfox
Springfox 是一個用于將 Swagger 集成到 Spring Boot 應(yīng)用程序中的庫。它允許你使用 Swagger 注解來描述和定義 API,自動生成和展示 API 文檔,并提供一個交互式的 UI 界面來測試和探索 API。
具體來說,Springfox 提供了以下功能和組件:
自動生成 API 文檔:在 Spring Boot 應(yīng)用程序中使用 Springfox,它會自動解析你的 API 控制器和注解,并生成符合 Swagger 規(guī)范的 API 文檔。
Swagger UI 支持:Springfox 集成了 Swagger UI,它提供了一個漂亮而易于使用的交互式界面,用于瀏覽和測試 API。你可以通過訪問
/swagger-ui.html
路徑來訪問 Swagger UI。API 注解支持:Springfox 支持所有的 Swagger 注解,例如
@Api
、@ApiOperation
、@ApiParam
等。你可以在你的 API 控制器和模型類中使用這些注解來定義 API 的結(jié)構(gòu)、操作、參數(shù)等信息。API 文檔自定義:Springfox 提供了很多配置選項,可以定制生成的 API 文檔的外觀和行為。你可以通過配置類和屬性來修改標(biāo)題、版本、路徑等信息,并應(yīng)用各種定制化的樣式和模板。
使用 Springfox,你可以輕松地將 Swagger 集成到 Spring Boot 應(yīng)用程序中,并自動生成和展示 API 文檔。這樣,你可以更方便地開發(fā)、測試和文檔化你的 RESTful API。
Springfox參考文檔:http://springfox.github.io/springfox/docs/current/
截止到2023年7月15日10:44:32,最新版本為3.0.0,那就以該版本為例演示SpringBoot的集成過程。
2.1Maven依賴
<dependency>
? <groupId>io.springfox</groupId>
? <artifactId>springfox-boot-starter</artifactId>
? <version>3.0.0</version>
</dependency>
2.2Swagger配置類
下面這段代碼是官網(wǎng)的寫法,我們先來看注釋看一下代碼的作用是什么。
package springfox.springconfig;
import com.fasterxml.classmate.TypeResolver;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.petstore.controller.PetController;
import java.util.List;
import static java.util.Collections.*;
import static springfox.documentation.schema.AlternateTypeRules.*;
@SpringBootApplication
// 啟用Springfox swagger 2
@EnableSwagger2
// 指示spring在哪里掃描API控制器
@ComponentScan(basePackageClasses = {PetController.class})
public class Swagger2SpringBoot {
?public static void main(String[] args) {
? ?SpringApplication.run(Swagger2SpringBoot.class, args);
?}
?@Bean
?public Docket petApi() {
? ?// Docket是Springfox提供的一個類,它用于配置Swagger的相關(guān)參數(shù)和API信息。Docket的主要作用是定義哪些接口需要生成文檔,
? ?// 并提供了一系列的配置選項來自定義生成的文檔。
? ?// Docket, Springfox的主要api配置機(jī)制在swagger規(guī)范2.0中被初始化
? ?return new Docket(DocumentationType.SWAGGER_2)
? ? // 配置 API 信息:通過 select() 方法,可以指定 API 的掃描規(guī)則和過濾條件,例如掃描的包路徑、特定的注解等??梢允褂?? ? ?? // apis() 方法來限定只生成指定的接口文檔。
? ? // select()返回一個ApiSelectorBuilder實例,以對通過swagger公開的端點進(jìn)行細(xì)粒度控制。
? ? ? ?.select()
? ? ? ?// api()允許使用謂詞選擇RequestHandler。這里的示例使用any謂詞(默認(rèn))。提供的開箱即用謂詞有any、none、
? ? ? ?// withClassAnnotation、withMethodAnnotation和baseppackage。
? ? ? ?.apis(RequestHandlerSelectors.any())
? ? ? ?// paths()允許使用謂詞選擇路徑。這里的示例使用any謂詞(默認(rèn))。我們開箱即用地為regex、ant、any、none提供了謂詞。
? ? ? ?.paths(PathSelectors.any())
? ? ? ?// 選擇器需要在配置api和路徑選擇器之后構(gòu)建。
? ? ? ?.build()
? ? ? ?// 當(dāng)servlet具有路徑映射時,添加servlet路徑映射。這將使用提供的路徑映射為路徑添加前綴。
? ? ? ?.pathMapping("/")
? ? ? ?// 方便的規(guī)則構(gòu)建器,在呈現(xiàn)模型屬性時用String替換LocalDate
? ? ? ?.directModelSubstitute(LocalDate.class, String.class)
? ? ? ?.genericModelSubstitutes(ResponseEntity.class)
? ? ? ?.alternateTypeRules(
?? ? ? ?// 使用類型參數(shù)替代具有一個類型參數(shù)的泛型類型的便利規(guī)則構(gòu)建器。
? ? ? ? ? ?newRule(typeResolver.resolve(DeferredResult.class,
? ? ? ? ? ? ? ?typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
? ? ? ? ? ? ? ?typeResolver.resolve(WildcardType.class)))
? ? ? ? // 指示是否需要使用默認(rèn)http響應(yīng)代碼的標(biāo)志。
? ? ? ?.useDefaultResponseMessages(false)
? ? ? ?// 允許全局重寫不同http方法的響應(yīng)消息。在這個例子中,我們覆蓋了所有GET請求的500錯誤碼。
? ? ? ?.globalResponses(HttpMethod.GET,
? ? ? ? ? ?singletonList(new ResponseBuilder()
? ? ? ? ? ? ? ?.code("500")
? ? ? ? ? ? ? ?.description("500 message")
? ? ? ? ? ? ? ?.representation(MediaType.TEXT_XML)
? ? ? ? ? ? ? ?.apply(r ->
? ? ? ? ? ? ? ? ? ?r.model(m ->
? ? ? ? ? ? ? ? ? ? ? ?m.referenceModel(ref ->
? ? ? ? ? ? ? ? ? ? ? ? ? ?ref.key(k ->
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?k.qualifiedModelName(q ->
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?q.namespace("some:namespace")
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 并指出它將使用響應(yīng)模型Error(將在其他地方定義)。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?.name("ERROR"))))))
? ? ? ? ? ? ? ?.build()))
? ? ? ? // 設(shè)置用于保護(hù)api的安全方案。支持的方案有ApiKey、BasicAuth和OAuth
? ? ? ?.securitySchemes(singletonList(apiKey()))
? ? ? ?// 這里我們使用ApiKey作為安全模式,它由名稱mykey標(biāo)識
? ? ? ?.securityContexts(singletonList(securityContext()))
? ? ? ?.enableUrlTemplating(true)
? ? ? ?// 配置全局參數(shù):通過 globalRequestParameters() 方法,可以定義全局的請求參數(shù),這些參數(shù)將適用于所有的接口文檔。
? ? ? ?.globalRequestParameters(
? ? ? ? ? ?singletonList(new springfox.documentation.builders.RequestParameterBuilder()
? ? ? ? ? ? ? ?.name("someGlobalParameter")
? ? ? ? ? ? ? ?.description("Description of someGlobalParameter")
? ? ? ? ? ? ? ?.in(ParameterType.QUERY)
? ? ? ? ? ? ? ?.required(true)
? ? ? ? ? ? ? ?.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
? ? ? ? ? ? ? ?.build()))
? ? ? ?.tags(new Tag("Pet Service", "All apis relating to pets"))
? ? ? ?.additionalModels(typeResolver.resolve(AdditionalModel.class));
?}
? ?/**
? ? * 在 Swagger 3.0.0 中,TypeResolver 是 Springfox 提供的一個類,它用于解析 Java 類型,將其轉(zhuǎn)換為 Swagger 的類型表示。
? ? * TypeResolver 的主要作用是幫助 Swagger 生成器(例如 Docket)在分析和解析 API 方法返回類型、請求參數(shù)類型、字段類型等時,
? ? * 將 Java 類型映射為 Swagger 規(guī)范中定義的類型。
? ? * 具體來說,TypeResolver 的作用包括:
? ? * 解析返回類型:當(dāng) Swagger 生成器分析 API 方法的返回類型時,它會使用 TypeResolver 來解析該返回類型,并將其轉(zhuǎn)換為 Swagger 規(guī)范中對應(yīng)的類型。這樣可以確保生成的 API 文檔中將正確顯示和描述該返回類型。
? ? * 解析請求參數(shù)類型:當(dāng) Swagger 生成器分析 API 方法的請求參數(shù)類型時,它也會使用 TypeResolver 來解析該參數(shù)類型。這樣可以確保生成的 API 文檔中針對每個請求參數(shù)都能正確標(biāo)記其類型和描述。
? ? * 解析字段類型:當(dāng) Swagger 生成器分析 Java 類型中的字段類型時,例如在模型類中,也會使用 TypeResolver 對字段類型進(jìn)行解析和映射。這樣可以確保生成的模型類在 API 文檔中能正確展示字段的類型信息。
? ? * 通過使用 TypeResolver,Swagger 3.0.0 可以根據(jù) Java 類型系統(tǒng)來生成準(zhǔn)確的 API 文檔。TypeResolver 將 Java 類型映射為適當(dāng)?shù)?Swagger 類型,確保在生成的文檔中能正確顯示和描述類型信息。
? ? * 需要注意的是,TypeResolver 可能還與其他配置類和插件一起使用,例如 ParameterBuilder、ModelConverter 等,以實現(xiàn)更復(fù)雜的類型解析和自定義處理。
? ? */
?@Autowired
?private TypeResolver typeResolver;
? ?/**
? ? * 在 Swagger 3.0.0 中,`ApiKey` 是一種身份驗證機(jī)制,用于在 API 請求中傳遞一個固定的密鑰或令牌。它的作用是確保只有提供了有效認(rèn)證密鑰的用戶才能訪問受保護(hù)的 API 資源。
? ? * 具體來說,`ApiKey` 的作用包括:
? ? * 1. 身份驗證:`ApiKey` 可以用于驗證用戶的身份。API 的開發(fā)者可以要求用戶在每個請求中提供一個有效的密鑰或令牌,以確認(rèn)其身份。
? ? * 2. 授權(quán)訪問:`ApiKey` 可以用于授權(quán)用戶訪問特定的 API 資源或功能。每個密鑰或令牌都可以根據(jù)其權(quán)限級別或角色來限制用戶所能訪問的資源。
? ? * 3. 安全性:使用 `ApiKey` 可以增加 API 的安全性。只有具有有效密鑰或令牌的用戶才能通過身份驗證并訪問受保護(hù)的資源。這可以防止未經(jīng)授權(quán)的訪問和濫用。
? ? * 在 Swagger 3.0.0 中,通過 `SecurityScheme` 以及 `@SecurityRequirement` 注解來定義和使用 `ApiKey`。`SecurityScheme` 用于定義 `ApiKey` 的名稱、位置和其他相關(guān)屬性,而 `@SecurityRequirement` 用于將 `ApiKey` 應(yīng)用到具體的 API 上。
? ? * 當(dāng)使用 `ApiKey` 進(jìn)行身份驗證時,在 Swagger UI 中的請求示例中會出現(xiàn)一個帶有用戶提供的密鑰或令牌的字段,以確保請求的有效性和安全性。
? ? * 需要注意的是,使用 `ApiKey` 時需要妥善保管密鑰或令牌,并在傳輸中使用適當(dāng)?shù)募用芎捅Wo(hù)措施,以防止泄露和濫用。
? ? */
?private ApiKey apiKey() {
? ?return new ApiKey("mykey", "api_key", "header");
?}
?private SecurityContext securityContext() {
? ?return SecurityContext.builder()
? ? ? ?.securityReferences(defaultAuth())
? ? ? ?// 這里我們使用安全方案mykey中定義的相同密鑰
? ? ? ?.forPaths(PathSelectors.regex("/anyPath.*"))
? ? ? ?.build();
?}
?List<SecurityReference> defaultAuth() {
? ?AuthorizationScope authorizationScope
? ? ? ?= new AuthorizationScope("global", "accessEverything");
? ?AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
? ?authorizationScopes[0] = authorizationScope;
? ?return singletonList(
? ? ? ?new SecurityReference("mykey", authorizationScopes));
?}
? ? /**
? ? * 在 Swagger 3.0.0 中,`SecurityConfiguration` 是 Springfox 提供的一個類,其作用是配置安全信息,包括認(rèn)證和授權(quán)相關(guān)的設(shè)置,用于在生成的 Swagger 文檔中添加安全定義。
? ? * 具體來說,`SecurityConfiguration` 的作用包括:
? ? * 1. 配置全局安全認(rèn)證:通過 `securityContexts()` 方法,可以設(shè)置全局的安全上下文。每個安全上下文通過 `SecurityContextBuilder` 對象定義,可以指定哪些接口需要進(jìn)行認(rèn)證,以及使用何種認(rèn)證方式。
? ? * 2. 配置全局安全方案:通過 `securitySchemes()` 方法,可以設(shè)置全局的安全方案,即認(rèn)證方式。常見的安全方案包括 OAuth2、ApiKey、Basic Authentication 等。每個安全方案通過 `SecurityScheme` 對象定義。
? ? * 3. 配置安全域:通過 `securityReferences()` 方法,可以設(shè)置安全引用,即安全方案在接口操作中的引用??梢灾付男┙涌谑褂媚姆N安全方案進(jìn)行認(rèn)證。
? ? * 通過 `SecurityConfiguration` 的配置,可以在 Swagger 生成的 API 文檔中添加認(rèn)證和授權(quán)信息,使用戶能夠了解和測試受保護(hù)的 API 資源。
? ? * 需要注意的是,`SecurityConfiguration` 根據(jù)項目實際需要進(jìn)行配置,在實際使用中可能會結(jié)合其他安全框架和工具進(jìn)行更加細(xì)粒度的安全控制。同時,安全方案的配置和使用也需要遵循相應(yīng)的安全最佳實踐和規(guī)范,以確保 API 的安全性和用戶的身份驗證。
? ? */
?@Bean
?SecurityConfiguration security() {
? ?return SecurityConfigurationBuilder.builder()
? ? ? ?.clientId("test-app-client-id")
? ? ? ?.clientSecret("test-app-client-secret")
? ? ? ?.realm("test-app-realm")
? ? ? ?.appName("test-app")
? ? ? ?.scopeSeparator(",")
? ? ? ?.additionalQueryStringParams(null)
? ? ? ?.useBasicAuthenticationWithAccessCodeGrant(false)
? ? ? ?.enableCsrfSupport(false)
? ? ? ?.build();
?}
? ? /**
? ? * 在 Swagger 3.0.0 中,`UiConfiguration` 是 Springfox 提供的一個類,用于配置 Swagger UI 的行為和樣式。
? ? * 具體來說,`UiConfiguration` 的作用包括:
? ? * 1. 配置頁面標(biāo)題和描述:通過 `title` 和 `description` 屬性,可以設(shè)置生成的 Swagger UI 頁面的標(biāo)題和描述信息,以便用戶更好地理解 API 文檔的用途和內(nèi)容。
? ? * 2. 配置文檔展示方式:通過 `deepLinking` 屬性,可以控制生成的 Swagger UI 頁面中是否使用深鏈接。深鏈接允許將 UI 頁面的狀態(tài)保存在 URL 中,以便用戶可以直接分享、保存和加載特定的視圖。
? ? * 3. 配置默認(rèn)展開操作:通過 `defaultModelsExpandDepth` 和 `defaultModelExpandDepth` 屬性,可以設(shè)置默認(rèn)展開的操作和模型的層級深度。這樣,用戶在打開 Swagger UI 時可以選擇是否展開某些操作或模型。
? ? * 4. 配置接口排序方式:通過 `docExpansion` 屬性,可以設(shè)置接口在 Swagger UI 頁面中的顯示方式,包括以列表方式或逐個展開方式進(jìn)行排序。
? ? * 5. 配置是否顯示請求授權(quán)功能:通過 `showRequestHeaders` 和 `showAuthorizeButton` 屬性,可以設(shè)置是否在 Swagger UI 中顯示請求頭和授權(quán)按鈕。這樣,用戶可以更方便地進(jìn)行請求授權(quán)和自定義請求頭。
? ? * 通過調(diào)整 `UiConfiguration` 的配置,可以根據(jù)項目需求來定制 Swagger UI 的展示行為和樣式,使其更符合項目的設(shè)計和用戶體驗。
? ? * 需要注意的是,`UiConfiguration` 的配置僅影響 Swagger UI 的前端展示,不會對實際的 API 實現(xiàn)產(chǎn)生直接影響。對于更高級的自定義需求,可以通過自定義 Swagger UI 的方式來修改和擴(kuò)展 UI 的樣式和行為。
? ? */
?@Bean
?UiConfiguration uiConfig() {
? ?return UiConfigurationBuilder.builder()
? ? ? ?.deepLinking(true)
? ? ? ?.displayOperationId(false)
? ? ? ?.defaultModelsExpandDepth(1)
? ? ? ?.defaultModelExpandDepth(1)
? ? ? ?.defaultModelRendering(ModelRendering.EXAMPLE)
? ? ? ?.displayRequestDuration(false)
? ? ? ?.docExpansion(DocExpansion.NONE)
? ? ? ?.filter(false)
? ? ? ?.maxDisplayedTags(null)
? ? ? ?.operationsSorter(OperationsSorter.ALPHA)
? ? ? ?.showExtensions(false)
? ? ? ?.showCommonExtensions(false)
? ? ? ?.tagsSorter(TagsSorter.ALPHA)
? ? ? ?.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
? ? ? ?.validatorUrl(null)
? ? ? ?.build();
?}
}
當(dāng)然上述配置內(nèi)容也可以和Spring Boot啟動類分來寫,這也是我在使用Swagger時常用的寫法。下面示例我只在配置類中定義了API文檔的類型格式和基本信息。
package com.example.swaggerdemo.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @Author yrz
* @create 2023/7/17 10:59
* @Description TODO
*/
/**
* 在早期版本的Swagger中,常常要求將@EnableSwagger2注解放置在Spring Boot應(yīng)用的啟動類上。但是,從Swagger 3.0開始,其對注解的使用進(jìn)行了一些調(diào)整。
* 對于Swagger 3.0及更高版本,我們需要使用其他注解來啟用Swagger API文檔框架。具體而言,我們可以使用以下注解之一:
* - @EnableSwagger2WebMvc:如果我們使用Spring MVC作為Web框架,則可以將此注解放置在配置類上,來啟用Swagger。
* - @EnableSwagger2WebFlux:如果我們使用Spring WebFlux作為Web框架,則可以將此注解放置在配置類上,來啟用Swagger。
* - @EnableOpenApi:這是Swagger 3.0引入的新注解,可以用于Spring Boot應(yīng)用中啟用Swagger。它可以用于既支持Spring MVC,也支持Spring WebFlux的應(yīng)用。
* 因此,根據(jù)你的具體情況,你可以選擇適當(dāng)?shù)淖⒔鈦韱⒂肧wagger API文檔框架,并將其放置在合適的配置類上。
*/
@EnableOpenApi
@Configuration
public class SwaggerConfig {
? ?@Bean
? ?public Docket createRestApi() {
? ? ? ?/**
? ? ? ? * 在Swagger中,Docket是Swagger的主要配置類,它用于初始化和配置Swagger的核心功能。在Docket初始化時,
? ? ? ? * 可以設(shè)置DocumentationType值來指定生成的API文檔的類型和格式。
? ? ? ? * DocumentationType是一個枚舉類型,它定義了幾種不同的API文檔標(biāo)準(zhǔn)。常見的DocumentationType值及其含義如下:
? ? ? ? * 1. SWAGGER_2:表示使用Swagger 2規(guī)范(舊版Swagger)生成API文檔。這是Swagger默認(rèn)的文檔類型,生成的文檔將符合Swagger 2的規(guī)范。
? ? ? ? * 2. OPENAPI_3_0_0:表示使用OpenAPI 3規(guī)范(Swagger的最新規(guī)范)生成API文檔。OpenAPI是Swagger 3版本開始使用的新規(guī)范,具有更多功能和靈活性。
? ? ? ? * 一般來說,如果使用較新版本的Swagger(3.0及以上),建議使用OPENAPI_3_0_0作為DocumentationType的值。如果使用早期版本的Swagger(2.0),則使用SWAGGER_2。
? ? ? ? * 通過設(shè)置DocumentationType的值,我們可以確保生成的API文檔符合相應(yīng)的規(guī)范,以便開發(fā)者更好地理解和使用API。
? ? ? ? */
? ? ? ?return new Docket(DocumentationType.OAS_30)
? ? ? ? ? ? ? ?.apiInfo(apiInfo())
? ? ? ? ? ? ? ?.select()
? ? ? ? ? ? ? ?.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
? ? ? ? ? ? ? ?.paths(PathSelectors.any())
? ? ? ? ? ? ? ?.build();
? ?}
? ?/**
? ? * ApiInfo類是Swagger API文檔框架中的一個輔助類,用于提供API文檔的基本信息,包括標(biāo)題、描述、版本號、許可證等。
? ? * ApiInfo類的作用是為API文檔提供更詳細(xì)的介紹和說明。通過配置ApiInfo,我們可以在生成的API文檔中添加以下信息:
? ? * 1. 標(biāo)題(Title):用于標(biāo)識API文檔的名稱或標(biāo)題。
? ? * 2. 描述(Description):對API文檔的簡要描述,可以說明API的功能、用途、使用方式等。
? ? * 3. 版本(Version):API文檔的版本號,用于標(biāo)識API的不同版本。
? ? * 4. 許可證(License):API文檔所屬的許可證類型,可以指明API的開放程度、使用限制等。
? ? * 5. 作者信息(Contact):關(guān)于API的作者或維護(hù)者的聯(lián)系信息,如姓名、電子郵件等。
? ? * 6. 參考鏈接(Terms of service URL):提供一條指向API相關(guān)信息或條款的鏈接。
? ? * 通過配置ApiInfo類,我們可以向API文檔添加更多詳細(xì)信息,方便開發(fā)者理解和使用API。這些信息將在Swagger的可視化界面中顯示,并提供給開發(fā)者參考和查閱。
? ? * @return
? ? */
? ?private ApiInfo apiInfo() {
? ? ? ?return new ApiInfoBuilder()
? ? ? ? ? ? ? ?.title("Swagger接口文檔")
? ? ? ? ? ? ? ?.description("如有疑問,請聯(lián)系開發(fā)工程師")
? ? ? ? ? ? ? ?.contact(new Contact("yrz", "", "yangruizeng@qq.com.cn"))
? ? ? ? ? ? ? ?.version("1.0")
? ? ? ? ? ? ? ?.build();
? ?}
}
2.2.1問題1
完成配置類可以先啟動一下Spring Boot項目,此時會有意外驚喜,啟動報錯:Failed to start bean 'documentationPluginsBootstrapper'
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.27.jar:5.3.27]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.27.jar:5.3.27]
報錯信息顯示“documentationPluginsBootstrapper”bean啟動失敗,報了一個空指針異常,跟蹤代碼吧,找了半天發(fā)現(xiàn)是
public interface RequestHandler extends Comparable<RequestHandler> {
...
@SuppressWarnings({"rawtypes", "unchecked"})
?static String sortedPaths(PatternsRequestCondition patternsCondition) {
? ?TreeSet<String> paths = new TreeSet<>(patternsCondition.getPatterns());
? ?return paths.stream()
? ? ? ?.filter(Objects::nonNull)
? ? ? ?.collect(Collectors.joining(","));
?}
?...
}
該方法的參數(shù)PatternsRequestCondition為null,也就是Swagger在啟動時并沒有加載到PatternsRequestCondition實例。
PatternsRequestCondition類是Spring MVC中的一個類,它用于表示請求URL的模式條件。主要作用是匹配請求的URL路徑與預(yù)定義的模式進(jìn)行匹配,以確定是否能夠處理該請求。
在Spring MVC中,控制器方法通常使用@RequestMapping注解來定義處理請求的URL路徑。PatternsRequestCondition類就是用來解析和匹配這些URL路徑的。
PatternsRequestCondition類提供了以下功能:
解析URL模式:它可以解析@RequestMapping注解中的value或path屬性值,將其轉(zhuǎn)化為一個包含多個URL模式的集合。每個URL模式可以包含固定的路徑,以及占位符(例如/{id})和通配符(例如/*)。
匹配URL路徑:根據(jù)預(yù)定義的URL模式,PatternsRequestCondition類可以將請求的URL路徑與這些模式進(jìn)行匹配。它使用Ant風(fēng)格的路徑匹配規(guī)則,支持通配符(*)和占位符({var})來進(jìn)行模式匹配。
條件合并:PatternsRequestCondition類還支持條件合并的功能,可以將多個PatternsRequestCondition對象進(jìn)行合并,以實現(xiàn)更復(fù)雜的匹配邏輯。例如,可以將基于URL和請求方法的模式條件合并在一起。
通過使用PatternsRequestCondition類,Spring MVC能夠根據(jù)定義的URL模式,準(zhǔn)確地匹配請求的URL路徑,并將請求分發(fā)給適當(dāng)?shù)目刂破鞣椒ㄟM(jìn)行處理。這有助于實現(xiàn)靈活且精確的請求URL映射和路由。
反觀Swagger的路徑匹配策略,它是由PathSelectors 這個類決定的,在 Swagger 3.0.0 中,PathSelectors 的作用是用于過濾要在 Swagger 文檔中顯示的 API 路徑。它可以幫助開發(fā)者定制需要包含或排除的 API 路徑,以便在生成的 Swagger 文檔中只展示感興趣的部分。
具體來說,PathSelectors 通過提供一些靜態(tài)方法來創(chuàng)建 PathSelector 對象。這些靜態(tài)方法包括:
any()
:選擇所有的 API 路徑,不進(jìn)行過濾。none()
:不選擇任何 API 路徑,即排除所有路徑。regex(String regex)
:選擇與給定正則表達(dá)式匹配的 API 路徑。ant(String antPattern)
:選擇與給定 Ant 風(fēng)格的路徑模式匹配的 API 路徑。
例如,如果想要只在 Swagger 文檔中展示以 /api
開頭的 API 路徑,可以使用 PathSelectors.ant("/api/**")
。
在使用 PathSelectors
的時候,一般是通過 Docket
對象的 select
方法來設(shè)置,示例如下:
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
? ?@Bean
? ?public Docket api() {
? ? ? ?return new Docket(DocumentationType.SWAGGER_2)
? ? ? ? ? ? ? ?.select()
? ? ? ? ? ? ? ?.paths(PathSelectors.ant("/api/**"))
? ? ? ? ? ? ? ?.build();
? ?}
}
在上述示例中,通過 PathSelectors.ant("/api/**")
方法,只選擇以 /api
開頭的 API 路徑進(jìn)行展示。
需要注意的是,PathSelectors
提供的方法只能進(jìn)行簡單的路徑過濾,并不支持進(jìn)一步的邏輯組合,如 AND 或 OR 運算。如果需要更復(fù)雜的路徑過濾邏輯,可以自定義實現(xiàn)相應(yīng)的 Predicate
對象,并使用 .paths(customPredicate)
方法來設(shè)置。
綜上所述,啟動報錯Swagger和Spring MVC的路徑匹配策略不一致導(dǎo)致的。那么修改Spring MVC路徑匹配策略,在配置文件中添加如下配置,問題解決。
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
2.2.2問題2
如果你的項目中引用了
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
那么你在啟動項目時,2.1.1的問題就會又出現(xiàn)了,debug吧,定位到
public class WebMvcPatternsRequestConditionWrapper
? ?implements springfox.documentation.spring.wrapper.PatternsRequestCondition<PatternsRequestCondition> {
? ?...
? ? @Override
?public Set<String> getPatterns() {
? ?return this.condition.getPatterns().stream()
? ? ? ?.map(p -> String.format("%s/%s", maybeChompTrailingSlash(contextPath), ?maybeChompLeadingSlash(p)))
? ? ? ?.collect(Collectors.toSet());
?}
?...
}
該方法的condition為null導(dǎo)致的問題,condition為WebMvcPatternsRequestConditionWrapper的成員變量,也就是在WebMvcPatternsRequestConditionWrapper初始化時,condition就為null。追根溯源,condition來源于
public class WebMvcRequestHandlerProvider implements RequestHandlerProvider {
?private final List<RequestMappingInfoHandlerMapping> handlerMappings;
?private final HandlerMethodResolver methodResolver;
?private final String contextPath;
?...
}
中的private final List<RequestMappingInfoHandlerMapping> handlerMappings;RequestMappingInfoHandlerMapping有五個子類(AbstractWebMvcEndpointHandlerMapping、AdditionalHealthEndpointPathsWebMvcHandlerMapping、CloudFoundryWebEndpointServletHandlerMapping、ControllerEndpointHandlerMapping、WebMvcEndpointHandlerMapping)來自于spring-boot-starter-actuator的jar包中,這些類都是 Spring Boot Actuator 框架中的處理器映射器,用于映射請求到相應(yīng)的 Actuator 端點處理器。下面分別解釋每個映射器的作用:
AbstractWebMvcEndpointHandlerMapping:是一個抽象基類,它定義了通用的方法和邏輯,用于處理 Spring Boot Actuator 中的端點請求映射。
AdditionalHealthEndpointPathsWebMvcHandlerMapping:用于將特定路徑與 HealthEndpoint 相關(guān)聯(lián),提供了額外的健康檢查信息。例如,可以將
/health
映射到/actuator/health
端點。CloudFoundryWebEndpointServletHandlerMapping:專為部署在 Cloud Foundry 平臺上的應(yīng)用程序設(shè)計的映射器。它通過解析 Cloud Foundry 平臺提供的信息,自動將請求映射到相應(yīng)的 Actuator 端點。
ControllerEndpointHandlerMapping:用于映射帶有
@Endpoint
注解的控制器端點。這些控制器端點可以用于自定義的業(yè)務(wù)邏輯,并暴露為 Actuator 端點。WebMvcEndpointHandlerMapping: 是 Actuator 的核心處理器映射器,用于將請求映射到標(biāo)準(zhǔn)的 Actuator 端點處理器。它解析并匹配請求路徑,并將請求映射到相應(yīng)的 Actuator 端點進(jìn)行處理。
這些映射器都是為了實現(xiàn) Actuator 端點的請求映射和處理而存在的。它們負(fù)責(zé)解析請求路徑、匹配請求,選擇合適的處理器方法,并最終執(zhí)行請求處理邏輯。每個映射器都有不同的特定用途,并在 Actuator 框架中扮演重要的角色,提供健康檢查、監(jiān)控和管理等功能。
在WebMvcRequestHandlerProvider類中打斷點,發(fā)現(xiàn)Swagger啟動時會加載三個Actuator 映射器,
Actuator映射器在一堆lambda表達(dá)式操作后并不能轉(zhuǎn)化成WebMvcPatternsRequestConditionWrapper對象,然后調(diào)用WebMvcRequestHandler 類中的 getPatternsCondition() 方法。
在生成 Swagger 文檔時,springfox-swagger 庫會掃描應(yīng)用程序中的控制器方法,并通過 WebMvcRequestHandlerMapping
來解析和處理這些方法。在此過程中,getPatternsCondition()
方法會被調(diào)用,用于獲取控制器方法上的請求路徑條件。
getPatternsCondition()
方法返回的是一個 PatternsRequestCondition
對象,其中包含了控制器方法的請求路徑模式。這些模式信息會被 springfox-swagger 庫使用,用于構(gòu)建 Swagger 文檔的路徑信息,包括生成 API 文檔的接口路徑。
總之,WebMvcRequestHandler
類的 getPatternsCondition()
方法在 springfox-swagger 庫中用于構(gòu)建 Swagger 文檔時被調(diào)用,用于獲取控制器方法的請求路徑模式信息,以便生成對應(yīng)的 API 文檔路徑。
繼續(xù)執(zhí)行斷點,會發(fā)現(xiàn)沒有AbstractWebMvcEndpointHandlerMapping的實例
所以需要注冊Actuator控制器的實例,在配置類中添加如下配置:
? @Bean
? ?public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
? ? ? ?List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
? ? ? ?Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
? ? ? ?allEndpoints.addAll(webEndpoints);
? ? ? ?allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
? ? ? ?allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
? ? ? ?String basePath = webEndpointProperties.getBasePath();
? ? ? ?EndpointMapping endpointMapping = new EndpointMapping(basePath);
? ? ? ?boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
? ? ? ?return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
? ?}
? ?private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
? ? ? ?return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
? ?}
問題解決,項目可以正常啟動!接下來就訪問swagger-ui的頁面http://localhost:8080/swagger-ui/index.html。
2.3Swagger UI配置類
這段代碼是一個 Swagger UI 的配置類(Swagger源碼),用于配置 Swagger UI 的訪問路徑和資源處理。
作用如下:
構(gòu)造器:接收一個 baseUrl 參數(shù),用于指定 Swagger UI 的根路徑。
addResourceHandlers 方法:重寫 WebMvcConfigurer 接口的該方法,用于添加資源處理器。在這里,它配置了一個資源處理器,用于處理 Swagger UI 的靜態(tài)資源文件。
addResourceHandler(baseUrl + "/swagger-ui/**"):指定了 Swagger UI 的資源路徑模式和匹配規(guī)則。
addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/"):指定了 Swagger UI 資源文件的存放位置,通常是在項目的 classpath 下的 webjars 目錄。
resourceChain(false):禁用資源鏈的自動配置,以確保能夠直接訪問到 Swagger UI 的靜態(tài)資源文件。
addViewControllers 方法:重寫 WebMvcConfigurer 接口的該方法,用于添加視圖控制器。在這里,它配置了一個視圖控制器,用于將 Swagger UI 的訪問重定向到具體的 HTML 頁面。
registry.addViewController(baseUrl + "/swagger-ui/"):指定了 Swagger UI 的訪問路徑。
setViewName("forward:" + baseUrl + "/swagger-ui/index.html"):設(shè)置視圖名稱,將該請求轉(zhuǎn)發(fā)到具體的 Swagger UI 的 HTML 頁面。
通過使用這段代碼,你可以將 Swagger UI 集成到 Spring Boot 應(yīng)用程序中,并配置 Swagger UI 的訪問路徑和資源處理。這樣,在運行應(yīng)用程序并訪問相應(yīng)的路徑時,你將能夠在瀏覽器中看到 Swagger UI 的界面,并瀏覽、測試和探索你的 API 文檔。
package springfox.boot.starter.autoconfigure;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
// tag::swagger-ui-configurer[]
public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
?private final String baseUrl;
?public SwaggerUiWebMvcConfigurer(String baseUrl) {
? ?this.baseUrl = baseUrl;
?}
?@Override
?public void addResourceHandlers(ResourceHandlerRegistry registry) {
? ?String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
? ?registry.
? ? ? ?addResourceHandler(baseUrl + "/swagger-ui/**")
? ? ? ?.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
? ? ? ?.resourceChain(false);
?}
?@Override
?public void addViewControllers(ViewControllerRegistry registry) {
? ?registry.addViewController(baseUrl + "/swagger-ui/")
? ? ? ?.setViewName("forward:" + baseUrl + "/swagger-ui/index.html");
?}
}
// end::swagger-ui-configurer[]
2.3.1重寫Swagger UI配置類
要自定義 Swagger UI 頁面的訪問路徑,可以按照以下步驟進(jìn)行操作:
創(chuàng)建一個自定義的 Swagger UI 配置類,命名為
import org.springframework.util.StringUtils;CustomSwaggerUiConfig
(或者根據(jù)您的喜好選擇一個合適的類名)。
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class CustomSwaggerUiConfig implements WebMvcConfigurer {
? ?private final String basePath;
? ?public CustomSwaggerUiConfig(String basePath) {
? ? ? ?this.basePath = basePath;
? ?}
? ?@Override
? ?public void addViewControllers(ViewControllerRegistry registry) {
? ? ? ?registry.addViewController(basePath + "/my-swagger")
? ? ? ? ? ? ? ?.setViewName("redirect:/swagger-ui/index.html");
? ?}
}在新的配置類中,重寫
addViewControllers()
方法,并根據(jù)需要自定義您的 Swagger UI 訪問路徑。在這個例子中,我們使用/my-swagger
作為自定義的 Swagger UI 路徑,并將其重定向到/swagger-ui/index.html
頁面。在主配置類(通常是指 Spring Boot 的啟動類)中,將自定義的 Swagger UI 配置類注入為一個 Bean。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfig {
? ?@Value("${server.servlet.context-path:}")
? ?private String contextPath;
? ?@Bean
? ?public CustomSwaggerUiConfig swaggerUiConfig() {
? ? ? ?return new CustomSwaggerUiConfig(contextPath);
? ?}
? ?// 其他配置和 Bean
}啟動應(yīng)用程序并訪問自定義的 Swagger UI 頁面。在這個例子中,您可以通過訪問
http://localhost:8080/<contextPath>/my-swagger
來訪問自定義的 Swagger UI 頁面。請注意,<contextPath>
是您配置的應(yīng)用程序上下文路徑。
通過以上步驟,您就可以自定義 Swagger UI 的訪問路徑,并通過新定義的路徑來訪問 Swagger UI。
3Controller層與Model層注解使用
@Api
使用場景
在 Rest 接口類上邊使用。
概述
標(biāo)記類為 Swagger 資源類,運行時有效。
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value String “” 隱式設(shè)置操作的標(biāo)記,遺留支持(讀取 description)
tags String[] “” 對接口進(jìn)行分組
produces String “” 采用逗號分隔的 content types,例如:application/json,application/xml 生成JSON和XML的輸出
consumes String “” 采用逗號分隔的 content types,例如: application/json,application/xml 會接收J(rèn)SON和XML的輸入
protocols String “” 采用逗號分隔的可用協(xié)議,例如:http,https,ws,wss
authorizations Authorization[] “” 授權(quán)列表
hidden boolean false 隱藏此資源下的操作, 和 @ApiOperation 注解中的 hidden 組合使用可以隱藏改接口
@ApiOperation
使用場景
在 Rest 接口上使用
概述
描述針對特定路徑的操作,通常是 HTTP 方法。具有等效路徑的操作被分到單個分組中。HTTP 方法和路徑的組合創(chuàng)建了一個獨特的操作
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value String 接口簡要說明,120字符或更少
notes String “” 接口詳細(xì)描述
tags String[] “” tag 列表,可用于按自愿或任何其它限定符對操作進(jìn)行邏輯分組
response Class<?> Void.class 接口返回類型
responseContainer String “” 聲明包裝響應(yīng)的容器。有效值為 List,Set,Map,任何其它值都將被忽略
responseReference String “” 指定對響應(yīng)類型的引用,本地/遠(yuǎn)程引用,并將覆蓋任何其它指定的response()類
httpMethod String “” 請求方式:“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”,如果未指定則使用除"PATH"之外的其它所有
nickname String “” 第三方工具使用operationId來唯一表示此操作
produces String “” 采用逗號分隔的 content types 類型的返回數(shù)據(jù),例如:application/json,application/xml
consumes String “” 采用逗號分隔的 content types 類型的入?yún)?shù)據(jù)類型,例如:application/json,application/xml
protocols String “” 指定協(xié)議類型:http,https,ws,wss,多個協(xié)議使用逗號進(jìn)行分隔
authorizations Authorization[] @Authorization(value = “”) 獲取此操作的授權(quán)列表
hidden boolean false 是否隱藏操作列表中的操作
responseHeaders ResponseHeader[] @ResponseHeader(name = “”, response = Void.class) 指定 response header 信息列表
code int 200 HTTP返回狀態(tài)碼
extensions Extension[] @Extension(properties = @ExtensionProperty(name = “”, value = “”)) 可選的擴(kuò)展數(shù)組
@ApiImplicitParams 和 @ApiImplicitParam
@ApiImplicitParams
使用場景
在 Rest 接口方法上使用來指定請求參數(shù)
概述
在 Rest 接口方法上使用來指定請求參數(shù)
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value ApiImplicitParam[] API 可用的參數(shù)列表
@ApiImplicitParam
使用場景
場景一:在 Rest 接口上單獨使用
@ApiImplicitParam 在 Rest 接口上單獨使用的時候,表示單個請求參數(shù)
場景二:在 Rest 接口上和 @ApiImplicitParams 組合使用 @ApiImplicitParam 在 Rest 接口上和 @ApiImplicitParams 組合時候,表示多個請求參數(shù)
概述
表示 Rest 接口的單個請求參數(shù),可與 @ApiImplicitParams 組合使用來表示多個請求參數(shù)
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
name String “” 參數(shù)名稱(實體類字段名稱)
value String “” 參數(shù)簡要說明
defaultValue String “” 描述參數(shù)的默認(rèn)值
allowableValues String “” 限制此參數(shù)接收的值,可使用的值或值得范圍
required boolean false 指定是否為必填參數(shù),false:非必傳參數(shù); true:必傳參數(shù)
access String “” 參數(shù)過濾,參考: io.swagger.core.filter.SwaggerSpecFilte
allowMultiple boolean false 指定參數(shù)是否可以通過多次出現(xiàn)來接收多個值
dataType String “” 參數(shù)的數(shù)據(jù)類型,可以使類名或原始數(shù)據(jù)類型
dataTypeClass Class<?> Void.class 參數(shù)的類,如果提供則覆蓋 dataType
paramType String “” 參數(shù)的參數(shù)類型,有效值為 path, query, body, header, form
example String “” 非請求體(body)參數(shù)的單個請求示例
examples Example @Example(value = @ExampleProperty(mediaType = “”, value = “”)) 參數(shù)示例,僅適用于 BodyParameters(請求體類型的)
type String “” 添加覆蓋檢測到的類型的功能
format String “” 添加提供自定義格式的功能
allowEmptyValue boolean false 添加將 format 設(shè)置為空的功能
readOnly boolean false 添加被指定為只讀的能力
collectionFormat String “” 添加使用 array 類型 collectionFormat 的功能
@ApiModel 和 @ApiModelProperty
@ApiModel
使用場景
在實體類上邊使用,標(biāo)記類時swagger的解析類
概述
提供有關(guān)swagger模型的其它信息,類將在操作中用作類型時自動內(nèi)省
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value String 類名 為模型提供備用名稱
description String “” 提供詳細(xì)的類描述
parent Class<?> parent Void.class 為模型提供父類以允許描述繼承關(guān)系
discriminatory String “” 支持模型繼承和多態(tài),使用鑒別器的字段的名稱,可以斷言需要使用哪個子類型
subTypes Class<?>[] {} 從此模型繼承的子類型數(shù)組
reference String “” 指定對應(yīng)類型定義的引用,覆蓋指定的任何其他元數(shù)據(jù)
@ApiModelProperty
使用場景
使用在被 @ApiModel 注解的模型類的屬性上
概述
添加和操作模型屬性的數(shù)據(jù)
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value String “” 屬性簡要說明
name String “” 運行覆蓋屬性的名稱。重寫屬性名稱
allowableValues String “” 限制參數(shù)可接收的值,三種方法,固定取值,固定范圍
access String “” 過濾屬性,參閱:io.swagger.core.filter.SwaggerSpecFilter
notes String “” 目前尚未使用
dataType String “” 參數(shù)的數(shù)據(jù)類型,可以是類名或原始數(shù)據(jù)類型,此值將覆蓋從類屬性讀取的數(shù)據(jù)類型
required boolean false 是否為必傳參數(shù),false:非必傳參數(shù); true:必傳參數(shù)
position int 0 允許在模型中顯示排序?qū)傩?/p>
hidden boolean false 隱藏模型屬性,false:不隱藏; true:隱藏
example String “” 屬性的示例值
readOnly boolean false 指定模型屬性為只讀,false:非只讀; true:只讀
reference String “” 指定對應(yīng)類型定義的引用,覆蓋指定的任何其他元數(shù)據(jù)
allowEmptyValue boolean false 允許傳空值,false:不允許傳空值; true:允許傳空值
@ApiResponses 和 @ApiResponse
@ApiResponses 代碼示例 github 代碼示例: https://github.com/CoderFreeMan/swagger-demo
使用場景
在 Rest 接口上使用,用作返回值的描述
概述
一個包裝器,允許列出多個 ApiResponse,若果你需要描述單個 ApiResponse,你仍然必須使用此注解并將@ApiResponse 包裝在一個數(shù)組中
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
value ApiResponse[] ApiResponse 列表
@ApiResponse
使用場景
在 Rest 接口或類上和 @ApiResponses 組合使用,組裝返回參數(shù)說明
概述
描述操作的可能響應(yīng),這可用于描述 Rest API 調(diào)用中可能的成功和錯誤 code 碼。此注解可以在方法或類級別應(yīng)用;僅當(dāng)在方法級別或拋出時未定義相同代碼的@ApiResponse注解時才會解析類級別注解異常,如果響應(yīng)中使用了不同的響應(yīng)類,則可以通過將響應(yīng)類于響應(yīng)碼組合使用。注意swagger不允許單個響應(yīng)代碼的多個響應(yīng)類型。此注解不直接使用,單獨使用時swagger不會解析,應(yīng)該和ApiResponses組合使用。
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
code int 響應(yīng)的HTTP狀態(tài)碼
message String 伴隨響應(yīng)的人類可讀的消息
response Class<?> Void.class 用于描述消息有效負(fù)載的可選響應(yīng)類,對應(yīng)于響應(yīng)消息對象的 schema 字段
reference String “” 指定對響應(yīng)類型的引用,指定的應(yīng)用可以使本地引用,也可以是遠(yuǎn)程引用,將按原樣使用,并將覆蓋任何指定的response()類
responseHeaders ResponseHeader[] @ResponseHeader(name = “”, response = Void.class) 可能響應(yīng)的 header 列表
responseContainer String “” 聲明響應(yīng)的容器,有效值為List,Set,Map,任何其他值都將被忽略
@ResponseHeader
使用場景
作為 @ApiResponse 的屬性,作為返回數(shù)據(jù)的一部分,指定返回 header 信息
概述
作為返回數(shù)據(jù)的一部分提供返回數(shù)據(jù)的 header 信息
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
name String “” Header’s name.
description String “” response header 詳細(xì)描述
response Class<?> Void.class Header’s data type
responseContainer String “” 聲明包裝響應(yīng)的容器,有效值為List或Set,任何其他值都將被覆蓋
@ApiParam
使用場景
在 Rest 接口上或 Rest 接口參數(shù)前邊使用
概述
為 Rest 接口參數(shù)添加其它元數(shù)據(jù)(導(dǎo)入到 yapi 中不會被解析)
屬性
屬性名稱 數(shù)據(jù)類型 默認(rèn)值 說明
name String “” 參數(shù)名稱,參數(shù)名稱將從 filed/method/parameter 名稱中派生,但你可以覆蓋它,路徑參數(shù)必須始終命名為它們所代表的路徑部分
value String “” 參數(shù)簡單描述
defaultValue String “” 描述參數(shù)默認(rèn)值
allowableValues String “” 可接收參數(shù)值限制,有三種方式,取值列表,取值范圍
required boolean false 是否為必傳參數(shù), false:非必傳; true:必傳
access String “” 參數(shù)過濾,請參閱:io.swagger.core.filter.SwaggerSpecFilter
allowMultiple boolean false 指定參數(shù)是否可以通過多次出現(xiàn)來接收多個值
hidden boolean false 隱藏參數(shù)列表中的參數(shù)
example String “” 非請求體(body)類型的單個參數(shù)示例
examples Example @Example(value = @ExampleProperty(mediaType = “”, value = “”)) 參數(shù)示例,僅適用于請求體類型的請求
type String “” 添加覆蓋檢測到類型的功能
format String “” 添加提供自定義format格式的功能
allowEmptyValue boolean false 添加將格式設(shè)置為空的功能
readOnly boolean false 添加被指定為只讀的能力
collectionFormat String “” 添加使用 array 類型覆蓋 collectionFormat 的功能
@ExternalDocs
使用場景
使用外部文檔說明的時候使用,參數(shù),方法,屬性上可使用
概述
定義外部文檔說明
屬性
屬性名稱數(shù)據(jù)類型默認(rèn)值說明valueString“”目標(biāo)文檔的簡要描述,GFM語法可用于富文本表示urlString