首页 > 其他分享 >在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3

在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3

时间:2024-03-01 19:11:07浏览次数:20  
标签:description Spring Boot public V3 User id Tutorial Schema

SpringDoc V1 只支持到 Spring Boot 2.x

springdoc-openapi v1.7.0 is the latest Open Source release supporting Spring Boot 2.x and 1.x.

Spring Boot 3.x 要用 SpringDoc 2 / Swagger V3, 并且包名也改成了 springdoc-openapi-starter-webmvc-ui

SpringDoc V2 https://springdoc.org/v2/

配置

增加 Swagger 只需要在 pom.xml 中添加依赖

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

Spring Boot 启动时就会自动启用 Swagger, 从以下地址可以访问 接口形式(JSON, YAML)和WEB形式的接口文档

如果要关闭, 启用, 自定义接口地址, 在 application.yml 中添加配置

springdoc:
  api-docs:
    path: /v3/api-docs
    enabled: false

对应WEB地址的配置为

springdoc:
  swagger-ui:
    path: /swagger-ui.html
    enabled: false

因为WEB界面的显示基于解析JSON接口返回的结果, 如果api-docs关闭, swagger-ui即使enable也无法使用

在开发和测试环境启动服务时, 可以用VM参数分别启用

# in VM arguments
-Dspringdoc.api-docs.enabled=true -Dspringdoc.swagger-ui.enabled=true

使用注解

@Tag

Swagger3 中可以用 @Tag 作为标签, 将接口方法进行分组. 一般定义在 Controller 上, 如果 Controller 没用 @Tag 注解, Swagger3 会用Controller的类名作为默认的Tag, 下面例子用 @Tag 定义了一个“Tutorial”标签, 带有说明"Tutorial management APIs", 将该标签应用于TutorialController后, 在 Swagger3 界面上看到的这个 Controller 下面的方法集合就是 Tutorial.

@Tag(name = "Tutorial", description = "Tutorial management APIs")
@RestController
@RequestMapping("/api")
public class TutorialController {
  //...
}

也可以将 @Tag 添加到单独的方法上, 这样在 Swagger3 界面上, 就会将这个方法跟同样是 Tutorial 标签的其它方法集合在一起.

public class AnotherController {
  @Tag(name = "Tutorial", description = "Tutorial APIs")
  @PostMapping("/tutorials")
  public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
    //...
  }
}

@Operation

Swagger3中 @Operation注解用于单个API方法. 例如

public class MoreController {

  @Operation(
      summary = "Retrieve a Tutorial by Id",
      description = "Some description",
      tags = { "tutorials", "get" })
  @GetMapping("/tutorials/{id}")
  public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {
    //...
  }
}

tags = { "tutorials", "get" }可以将一个方法放到多个Tag分组中

@ApiResponses 和 @ApiResponse

Swagger3 使用 @ApiResponses 注解标识结果类型列表, 用@ApiResponse注解描述各个类型. 例如

    public class AnotherController {
    @ApiResponses({
        @ApiResponse(
                responseCode = "200",
                content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),
        @ApiResponse(
                responseCode = "404",
                description = "User not found.", content = { @Content(schema = @Schema()) })
    })
    @GetMapping("/user/{id}")
    public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {
        return null;
    }
}

@Parameter

@Parameter注解用于描述方法参数, 例如:

@GetMapping("/tutorials")
public ResponseEntity<Map<String, Object>> getAllTutorials(
  @Parameter(description = "Search Tutorials by title") @RequestParam(required = false) String title,
  @Parameter(description = "Page number, starting from 0", required = true) @RequestParam(defaultValue = "0") int page,
  @Parameter(description = "Number of items per page", required = true) @RequestParam(defaultValue = "3") int size) {
    //...
}

@Schema annotation

Swagger3 用 @Schema 注解对象和字段, 以及接口中的参数类型, 例如

@Schema(description = "Tutorial Model Information")
public class Tutorial {

  @Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "Tutorial Id", example = "123")
  private long id;

  @Schema(description = "Tutorial's title", example = "Swagger Tutorial")
  private String title;

  // getters and setters
}

accessMode = Schema.AccessMode.READ_ONLY用于在接口定义中标识字段只读

实例

定义接口

@Tag(
        name = "CRUD REST APIs for User Resource",
        description = "CRUD REST APIs - Create User, Update User, Get User, Get All Users, Delete User"
)
@Slf4j
@RestController
public class IndexController {

    @Operation(summary = "Get a user by its id")
    @GetMapping(value = "/user_get")
    public String doGetUser(
            @Parameter(name = "id", description = "id of user to be searched")
            @RequestParam(name = "id", required = true)
            String id) {
        return "doGetUser: " + id;
    }

    @Operation(summary = "Add a user")
    @PostMapping(value = "/user_add")
    public String doAddUser(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true)
            @RequestBody UserBO user) {
        return "doAddUser: " + user.getName();
    }
    
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),
            @ApiResponse(
                    responseCode = "404",
                    description = "User not found.", content = { @Content(schema = @Schema()) })
    })
    @GetMapping("/user/{id}")
    public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {
        return null;
    }
}

对于这行代码@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true),
因为 Swagger3 的 RequestBody 类和 Spring MVC 的 RequestBody 重名了, 所以在注释中不得不用完整路径, 比较影响代码格式. 在GitHub上有对这个问题的讨论(链接 https://github.com/swagger-api/swagger-core/issues/3628), 暂时无解.

定义对象

@Schema(description = "UserBO Model Information")
@Data
public class UserBO {

    @Schema(description = "User ID")
    private String id;
    @Schema(description = "User Name")
    private String name;
}

参考

标签:description,Spring,Boot,public,V3,User,id,Tutorial,Schema
From: https://www.cnblogs.com/milton/p/18047756

相关文章

  • div3笔记
     Problem-E-Codeforces这道题用了记录一个数末尾零的板子(敲重点)!!!再说一遍,简单博弈论就是贪心!1voidsolve(){2cin>>n>>m;3vector<int>a(n),b(n);4for(inti=0;i<n;i++)cin>>a[i];5intlen=0;//这组数字总共有几位,总长度6......
  • spring cloud gateway使用 uri: lb://方式配置时,服务名的特殊要求
    在gateway中配置uri配置有三种方式,包括第一种:ws(websocket)方式:uri:ws://localhost:9000第二种:http方式:uri:http://localhost:8130/第三种:lb(注册中心中服务名字)方式:uri:lb://brilliance-consumer  其中ws和http方式不容易出错,因为http格式比较固定,但是lb方式比......
  • SpringBoot定时任务:使用shedlock解决SpringBoot分布式定时任务
    第一步:引入shedlock包maven中pom文件添加如下配置:<dependency><groupId>net.javacrumbs.shedlock</groupId><artifactId>shedlock-spring</artifactId><version>4.33.0</version>使用其他版本</dependency>第二步:添加shedlock-p......
  • Spring Boot + liteflow 规则引擎,太香了!
    作者:豫州牧链接:https://juejin.cn/post/72967717700987453441、前言在日常的开发过程中,经常会遇到一些串行或者并行的业务流程问题,而业务之间不必存在相关性。在这样的场景下,使用策略和模板模式的结合可以很好的解决这个问题,但是使用编码的方式会使得文件太多,在业务的部分环......
  • Spring @Configuration 和 @Component 区别
    Spring@Configuration和@Component区别一句话概括就是@Configuration中所有带@Bean注解的方法都会被动态代理,因此调用该方法返回的都是同一个实例。 @Configuration注解:@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic@......
  • springboot应用中根据特定条件使用CommandLineRunner
    PS使用SpringBoot3.1.2进行测试1.使用@ConditionalOnProperty仅当特定属性存在或具有特定值时,注释@ConditionalOnProperty才会创建bean。在此示例中,仅当或文件中的CommandLineRunner属性db.init.enabled设置为true时才会执行application.propertiesapplication.ymlpac......
  • Spring Boot学习日记17
    尝试整合JDBC spring:datasource:username:rootpassword:123456url:jdbc:mysql://localhost:3306/mybatis?useSSL=true&userUniceode=true&characterEncoding=utf8driver-class-name:com.mysql.cj.jdbc.Driverpackagecom.example.spri......
  • Spring Boot学习日记9
    在springboot项目中的resources目录下新建一个文件application.yml编写一个实体类Dog;packagecom.example.springboot02configure.pojo;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;@Component//添加......
  • Spring Boot学习日记6
    @SpringBootConfiguration:SpringBoot的配置@Configuration:spring配置类@Component:说明这也是一个spring的组件@EnableAutoConfiguration:自动配置@AutoConfigurationPackage:自动配置包@Import({Registrar.class}):导入了选择器@Import({AutoConfigurationImportSelect......
  • Spring Boot学习日记7
    学会了配置springboot导入各种组件SpringBoot在启动的时候,从类路径下/META-INF/spring.factories获取指定的值将这些自动配置的类导入容器,自动配置类就会生效,帮我们进行自动配置以前我们需要自动配置的东西,现在不需要了整合javaEE,解决方案和自动配置的东西都在Spring-boot-......