使用springdoc-openapi快速生成openapi文档

2,323 阅读1分钟

springdoc-openapi是个专门用于自动化生成Spring Boot项目的API文档的工具,可以在SpringBoot V3以上版本使用。支持Swagger-ui、OpenAPI V3等功能。
官方文档地址

快速入门

SpringBoot项目中添加依赖

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.6.0</version>
</dependency>

增加一个Controller

@GetMapping("/hello")
public String hello() {
    return "hello";
}

访问http://localhost:8080/swagger-ui/index.html

image.png 访问http://localhost:8080/v3/api-docs 的结果如下

{
  "openapi": "3.0.1",
  "info": {
    "title": "OpenAPI definition",
    "version": "v0"
  },
  "servers": [
    {
      "url": "http://localhost:8080",
      "description": "Generated server url"
    }
  ],
  "paths": {
    "/hello": {
      "get": {
        "tags": [
          "hello-controller"
        ],
        "operationId": "hello",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "*/*": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {

  }
}

至此,使用默认配置项的springdoc-openapi已经生效了。

使用swagger3注解生成更加详细的接口文档

springdoc-openapi-starter-webmvc-ui中已经包含了swagger3的依赖,所以我们不需要再引入其他依赖。
使用swagger3注解的接口:

@GetMapping("/hello")
@Operation(summary = "hello api summary", description = "hello api description")
@Parameters({
        @Parameter(name = "name", description = "name of the person", example = "zhangsan")
})
public HelloDto hello(String name) {
    HelloDto helloDto = new HelloDto();
    helloDto.setName(name);
    helloDto.setMessage("hello to " + name);
    return helloDto;
}

使用swagger3注解的dto类

@Data
@Schema(name = "HelloDto",description = "hello dto description")
class HelloDto {
    @Schema(name = "name", description = "name of the person")
    private String name;

    @Schema(name = "message", description = "message to the person")
    private String message;
}

swagger-ui中的结果

image.png

image.png

常用的配置项

正常使用时,我们会对默认配置项做一些修改。下面是一些常用的配置项:

  • 指定需要扫描的包:springdoc.packages-to-scan springdoc.paths-to-match
  • 指定不需要扫描的包:springdoc.packages-to-exclude springdoc.paths-to-exclude
  • apidocs路径配置 springdoc.api-docs.path 默认路径是 /v3/api-docs
  • apidocs使能 springdoc.api-docs.enabled 默认值为true
  • swagger-ui路径配置 springdoc.swagger-ui.path 默认路径是 /swagger-ui/index.html
  • swagger-ui使能 springdoc.swagger-ui.enabled 默认值为true

注意事项

项目中如果包含SpringSecruity,需要放开api-docs和swagger-ui的路径,可以如下配置:

http.authorizeHttpRequests(
    registry -> {
      registry
          .requestMatchers(
              HttpMethod.GET,
              "/v3/api-docs/**",
              "/swagger-ui/**")
          .permitAll();
    });