使用SpringDoc编写API文档 - xinwu-yang/cube-java GitHub Wiki
不管是之前使用SpringFox或Knife4j的编写API文档的都可以迁移到SpringDoc。 SpringDoc 官方文档
首先删掉 SpringFox 或 Knife4j 依赖,引入 SpringDoc 依赖。
<!-- 包含UI界面 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.12</version>
</dependency>
<!-- 不包含UI界面 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
</dependency>
只要注入 OpenAPI 的 Bean 即可
@Bean
@ConditionalOnMissingBean
public OpenAPI openAPI() {
OpenAPI openAPI = new OpenAPI();
openAPI.info(new Info().title("Cube API")
.description("魔方快速开发平台API")
.version("v2.6.x")
.license(new License()
.name("Apache 2.0")
.url("https://www.apache.org/licenses/LICENSE-2.0")));
openAPI.externalDocs(new ExternalDocumentation().description("魔方开发文档").url("http://125.71.201.11:10086/"));
openAPI.components(new Components().securitySchemes(swaggerProperties.getSecuritySchemes()));
swaggerProperties.getSecuritySchemes().keySet().forEach(key -> openAPI.addSecurityItem(new SecurityRequirement().addList(key)));
return openAPI;
}
YML配置
springdoc:
api-docs:
path: /api-docs
cube:
swagger:
securitySchemes:
X-Access-Token:
type: APIKEY
in: HEADER
name: X-Access-Token
SpringDoc 稍微改动了相关注解,示例 SpringFox - SpringDoc 对应关系如下
@Api → @Tag
@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @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")
进行了上面简单的迁移步骤,即可访问 http://localhost:8080/cube/swagger-ui.html 文档页面。
当然很多时候我们不想把swagger页面集成到项目中,那么我们可以单独部署swagger页面。
访问 http://25.30.15.86 ,并在标题栏填写你自己的spirngdoc接口就能直接看到你的文档啦
Docker部署
version: "3"
services:
swagger:
image: swaggerapi/swagger-ui:v4.15.0
container_name: swagger-ui
restart: always
environment:
- SWAGGER_JSON_URL=http://25.30.15.6:8080/cube/api-docs
- DEFAULT_MODEL_RENDERING=model
- DEFAULT_MODELS_EXPAND_DEPTH=-1
- DEFAULT_MODEL_EXPAND_DEPTH=2
- DOC_EXPANSION=none
ports:
- 80:8080