Swagger3
Swagger 的實現: springfox、springdoc、knife4j,類似於 slf4j 和 log4j2、logback 的關系一樣。
准備
<!--SpringFox 貌似停更了-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--也可以使用 SpringDoc-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.13</version>
</dependency>
@EnableOpenApi
常用注解
| 注解 | 類 | 方法 | 屬性 |
|---|---|---|---|
| @Api(tags) | 標注一個類為 Swagger 資源, 設置資源名稱, 默認是類名 | ||
| @ApiOperation(value) | 標注一個請求, 設置該請求的名稱, 默認是方法名 | ||
| @ApiParam | (不常用) 僅用於 JAX-RS | ||
| @ApiImplicitParam | (常用) 功能同 @ApiParame, 可用於 Servlet | ||
| @ApiImplicitParams | 包裹多個參數描述注解 | ||
| @ApiModel | 標注一個實體類 | ||
| @ApiModelProperty | 標注實體屬性, 設置屬性的備注信息 | ||
| @ApiResponse | 描述響應碼,以及備注信息 | ||
| @ApiResponses | 包裹多個響應描述注解 | ||
| @ApiIgnore | 使swagger忽略某個資源 | 使swagger忽略某個接口 | 使swagger忽略某個屬性 |
摘自 springdoc 官網的注解對比:

SpringFox
配置文檔信息
// SpringFox 需要注入一個 Docket 對象配置文檔信息, springfox.documentation.spring.web.plugins.Docket 中默認配置了部分屬性
// springfox.documentation.spi.service.contexts.Defaults 中配置了一些基本內容
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.groupName("LearnSwagger")
.apiInfo(apiInfo())
.enable(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("測試文檔標題")
.contact(new Contact("XTvLi", "https://github.com/xtyuns", null))
.description("測試文檔描述信息")
.version("v1.0.0")
.build();
}
}
詳見 Docket 和 ApiInfo 的源碼
文檔資源過濾
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.groupName("LearnSwagger")
.select()
.paths(s -> s.startsWith("/v1"))
.build();
}
通過 paths 選取時可以使用 PathSelectors, 其中提供了 any()、none()、ant(antPattern)、regex(pathRegex) 方法。
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.groupName("LearnSwagger")
.select()
.apis(RequestHandlerSelectors.basePackage("com.xtyuns"))
.apis(requestHandler -> "index-controller".equals(requestHandler.groupName()))
.build();
}
// 等同於 (使用 and 連結多個選取方法)
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.groupName("LearnSwagger")
.select()
.apis(
RequestHandlerSelectors.basePackage("com.xtyuns")
.and(
requestHandler -> "index-controller".equals(requestHandler.groupName())
)
).build();
}
// 默認的 Selector
public static final ApiSelector DEFAULT
= new ApiSelector(
(withClassAnnotation(ApiIgnore.class).negate()).and(
(withMethodAnnotation(ApiIgnore.class).negate())), PathSelectors.any());
RequestHandlerSelectors 中也提供了 any()、none()、withClassAnnotation(cls)、withMethodAnnotation(cls) 方法。
requestHandler.groupName() 是類名稱的中划線表示法,RequestHandler 類中還有一些其他信息可用於進行斷言。
文檔分組
可以配置多個 Docket Bean, 必須使用 GroupName 進行區分。
配置示例

SpringDoc
springdoc 大多數配置都與 springfox 類似,如 Docket 變為了 OpenApi 或 GroupedOpenApi
授權
io.swagger.v3.oas.annotations.security.SecurityScheme
@RestController
@Tag(name = "springdoc & security")
@SecuritySchemes({
@SecurityScheme(
name = "byBearer",
type = SecuritySchemeType.HTTP,
scheme = "bearer"
),
@SecurityScheme(
name = "byApiKey",
type = SecuritySchemeType.APIKEY,
in = SecuritySchemeIn.HEADER,
paramName = "customerKey"
),
@SecurityScheme(
name = "byOAuth2Password",
type = SecuritySchemeType.OAUTH2,
flows = @OAuthFlows(
authorizationCode = @OAuthFlow(
authorizationUrl = "http://example.com/oauth2/authorize",
tokenUrl = "http://example.com/oauth2/token"
),
password = @OAuthFlow(
tokenUrl = "http://example.com/oauth2/token"
)
)
)
})
public class IndexController {
@Operation(
summary = "這是默認請求地址",
security = {
@SecurityRequirement(name = "byBearer")
},
responses = {
@ApiResponse(responseCode = "200", description = "請求成功, 響應: ok"),
@ApiResponse(responseCode = "500", description = "服務器內部出錯了")
}
)
@GetMapping("")
public ResponseEntity<String> index() {
return ResponseEntity.ok("ok");
}
}
- scheme type: Basic、Bearer
通過 OpenApi 定義 SecurityScheme: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#securitySchemeObject
相關閱讀
swaggere2 和 swagger3: https://blog.csdn.net/qq_35425070/article/details/105347336
springfox 到 springdoc 遷移指南: https://github.com/springfox/springfox/pull/3935
注解總覽: https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#quick-annotation-overview
spring gateway 統一配置 swagger: https://piotrminkowski.com/2020/02/20/microservices-api-documentation-with-springdoc-openapi/
自定義異常處理響應: https://blog.lanweihong.com/posts/1527/
