springdoc-openapi 的基本使用

概述

使用 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 文档

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿小乙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值