概述
使用 springdoc-openapi 可以快速为 springboot 项目生成规范的 API 文档,具体使用步骤如下:
依赖配置
在 pom.xml
加入内容,即可开始使用:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.9</version> </dependency>
然后在 Config 中配置基本的描述信息,如下:
@Configuration public class OpenApiConfig { @Bean public OpenAPI springOpenAPI() { return new OpenAPI() .info(new Info() .title("SpringDoc API Test") .description("SpringDoc Simple Application Test") .version("0.0.1")); } }
接下来在 Controller 中使用注解标记文本,如下:
@RestController(value = "/clients") @Tag(name = "/clients") public class ClientsRestController { @Operation(summary = "This method is used to get the clients.") @GetMapping public List<String> getClients() { return Arrays.asList("First Client", "Second Client"); } }
最后 Application.java
启动应用后,输入默认地址:http://localhost:8081/swagger-ui/index.html
即可看到文档:
在地址 http://localhost:8081/v3/api-docs
目录中,openAPI 3.0.1 文件,格式如下:
总结
很多从 swagger 2 过来的用户可能会好奇,为什么不使用 springfox 库来生成 API,我在这里简单总结一下
推荐使用 springdoc-openapi 的理由如下:
- springdoc-openapi 是 spring 官方出品,与 springboot 兼容更好(springfox 兼容有坑)
- springdoc-openapi 社区更活跃,springfox 已经 2 年没更新了
- springdoc-openapi 的注解更接近 OpenAPI 3 规范
综上所述,我个人还是更加推荐使用 springdoc-openapi 来自动化你项目的 API 文档