草庐IT

集成 Spring Doc 接口文档和 knife4j-SpringBoot 2.7.2 实战基础

程序员优雅哥 (youyacoder) 2023-04-16 原文

优雅哥 SpringBoot 2.7.2 实战基础 - 04 -集成 Spring Doc 接口文档和 knife4j

前面已经集成 MyBatis Plus、Druid 数据源,开发了 5 个接口。在测试这 5 个接口时使用了 HTTP Client 或 PostMan,无论是啥都比较麻烦:得自己写请求地址 URL、请求参数等,于是多年前就出现了 Swagger 这个玩意。Swagger 可以自动生成接口文档,还能很方便的测试各个接口。但不幸的是,MVN Repository 上面 Springfox Swagger2 的版本停止于 2020 年 7月,而写下这篇文章是 2022 年 8 月,已经两年过去没有动静了,与此同时,springdoc-openapi 悄然出现。

spring doc open api 支持 Open API 3、Swagger-ui等,可以很方便与 Spring Boot 整合,配置和使用与 Springfox Swagger2 类似。

1 集成 Spring Doc

1.1 添加依赖

springdoc-openapi 不是 Spring Framework 官方团队开发的,而是社区项目,没有包含在 spring-boot-dependencies 中。故需要先定义版本号:

<properties>
		....
    <springdoc-openapi-ui.version>1.6.9</springdoc-openapi-ui.version>
</properties>

添加依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>${springdoc-openapi-ui.version}</version>
</dependency>

该依赖里面使用了 swagger-ui,以HTML形式展示文档。

1.2 编写配置类

其实配置类写不写都可以,如果不写配置类,就通过注解定义文档信息就可以。创建类:com.yygnb.demo.config.SpringDocConfig

package com.yygnb.demo.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringDocConfig {

    private String title = "Hero SpringBoot Demo";
    private String description = "Hero Demo for usage of Spring Boot";
    private String version = "v0.0.1";
    private String websiteName = "Hero Website";
    private String websiteUrl = "http://www.yygnb.com";

    @Bean
    public OpenAPI heroOpenAPI() {
        return new OpenAPI()
                .info(new Info().title(title)
                        .description(description)
                        .version(version))
                .externalDocs(new ExternalDocumentation().description(websiteName)
                        .url(websiteUrl));
    }
}

上面的配置定义了展示的文档的信息,与界面上对应关系如下:

在配置文件中除了可以配置文档的信息,还可以配置文档分组、Authorization 等,在后面的企业级实战文章中会具体描写,将会在网关层 spring cloud gateway 中集成所有微服务的接口。

1.3 配置yml

在 application.yml 配置 springdoc:

# 接口文档
springdoc:
  packages-to-scan: com.yygnb.demo.controller
  swagger-ui:
    enabled: true

这两项不配置也可以,packages-to-scan 默认为启动类所在的路径;springdoc.swagger-ui.enabled 默认为true,配置后可以在不同的环境中开启或关闭。

1.4 添加注解

springdoc-openapi 与 springfox-swagger2 提供的注解有很大差别:

swagger 2 spring doc 描述
@Api @Tag 修饰 controller 类,类的说明
@ApiOperation @Operation 修饰 controller 中的接口方法,接口的说明
@ApiModel @Schema 修饰实体类,该实体的说明
@ApiModelProperty @Schema 修饰实体类的属性,实体类中属性的说明
@ApiImplicitParams @Parameters 接口参数集合
@ApiImplicitParam @Parameter 接口参数
@ApiParam @Parameter 接口参数

修改实体类 Computer,添加 springdoc-openapi 注解:

@Schema(title = "电脑")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Computer implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @Schema(title = "尺寸")
    private BigDecimal size;

    @Schema(title = "操作系统")
    private String operation;

    @Schema(title = "年份")
    private String year;
}

修改控制器 ComputerController,添加注解:

@Tag(name = "电脑相关接口")
@RequiredArgsConstructor
@RestController
@RequestMapping("/computer")
public class ComputerController {

    private final IComputerService computerService;

    @Operation(summary = "根据id查询电脑")
    @GetMapping("/{id}")
    public Computer findById(
            @Parameter(name = "id", required = true, description = "电脑id") @PathVariable Long id) {
        return this.computerService.getById(id);
    }

    @Operation(summary = "分页查询电脑列表")
    @Parameters(value = {
            @Parameter(name = "page", description = "页面,从1开始", example = "2"),
            @Parameter(name = "size", description = "每页大小", example = "10")
    })
    @GetMapping("/find-page/{page}/{size}")
    public Page<Computer> findPage(@PathVariable Integer page, @PathVariable Integer size) {
        return this.computerService.page(new Page<>(page, size));
    }

    @Operation(summary = "新增电脑")
    @PostMapping()
    public Computer save(@RequestBody Computer computer) {
        computer.setId(null);
        this.computerService.save(computer);
        return computer;
    }

    @Operation(summary = "根据id修改电脑")
    @PutMapping("/{id}")
    public Computer update(
            @Parameter(name = "id", required = true, description = "电脑id") @PathVariable Long id,
            @RequestBody Computer computer) {
        computer.setId(id);
        this.computerService.updateById(computer);
        return computer;
    }

    @Operation(summary = "根据id删除电脑")
    @DeleteMapping("/{id}")
    @Parameter(name = "id", required = true, description = "电脑id")
    public void delete(@PathVariable Long id) {
        this.computerService.removeById(id);
    }
}

1.5 运行测试

启动服务,在浏览器中访问:

http://localhost:9099/swagger-ui/index.html

2 api-docs

在文档标题下面有一个小链接:/v3/api-docs,点击该链接,会在新页面中显示一大坨 JSON 数据。

看似很无聊的数据,却有着重大意义,swagger-ui 就是通过这些数据渲染出页面的。此外,这些JSON数据在某种程度上可以简化前端的开发及前后端网络请求的工作量。

hero-admin-ui

优雅哥正在开发的基于 Vue 3 + TypeScript 的开源项目 hero-admin-ui,其特色就是基于 JSON Schema 的表单和列表。通过 JSON Schema 可以快速渲染出一个列表、表单,甚至是搜索页和详情表单页。如果独立使用 hero-admin-ui,需要手动编写 JSON Schema,但如果后端接口整合了 Swagger 或 Spring Doc,上面 api-docs 返回的 JSON,就包含了 JSON Schema,二者结合可以快速实现搜索页、表单页等。目前 hero-admin-ui 已发布在 npmjs 上,也已经提交到 github上,大家可以搜索关键字 hero-admin-ui 查看。在后面的实战篇中,前端部分将会使用这个组件库实现前端页面。

3 自定义配置

在 ”1.2 编写配置类“ 一节,文档信息都是写死在代码中的,如果多个微服务都要集成 spring doc,可以把前面写的 SpringDocConfig 提取到公共模块中,通过maven 依赖引用,在 application.yml 中配置不同的变量。

3.1 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

配置该依赖的目的是在编写 application.yml 时,自定义的属性有代码提示。它会生成配置元数据,无需自己手动编写。

3.2 定义配置的实体类

创建 com.yygnb.demo.config.DocInfo,将 SpringDocConfig 中写死的属性都移到这个配置实体类中:

@Data
@Component
@ConfigurationProperties(prefix = "doc-info")
public class DocInfo {

    private String title = "Demo Title";
    private String description = "Demo Description";
    private String version = "v0.0.1";
    private String websiteName = "Demo Website";
    private String websiteUrl = "http://www.yygnb.com";
}

注解 @ConfigurationProperties(prefix = "doc-info") 声明配置属性,在 application.yml 配置时就可以使用 doc-info。

3.3 重构 SpringDocConfig

在 SpringDocConfig 中引入 DocInfo,并通过构造函数进行注入:

@RequiredArgsConstructor
@Configuration
public class SpringDocConfig {

    private final DocInfo docInfo;

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title(docInfo.getTitle())
                        .description(docInfo.getDescription())
                        .version(docInfo.getVersion()))
                .externalDocs(new ExternalDocumentation().description(docInfo.getWebsiteName())
                        .url(docInfo.getWebsiteUrl()));
    }
}

补充一个小点:注解 @RequiredArgsConstructor 是 lombok 中提供的,它等价于在类中编写了方法:

public SpringDocConfig(DocInfo docInfo) {
    this.docInfo = docInfo;
}

构造注入时,在构造函数中写大量的属性,毫无意义。既然已经使用了 @Data 注解,为啥不用 @RequiredArgsConstructor 呢?

3.4 使用自定义配置

自定义配置已经完成,可以在 application.yml 中使用 DocInfo 对应的配置了:

doc-info:
  title: SpringBoot Demo演示
  description: 学习 Spring Boot 2.7.2

DocInfo 所有属性都定义了默认值,在 application.yml 可以覆盖默认值,如上面的 titledescription 属性。重启服务查看运行效果:

4 集成 knife4j

在之前 springfox-swagger 的时代,很多同学不喜欢 swagger-ui 的界面风格,会集成 knife4j 的 ui。Spring Doc 也可以集成 knife4j。

如果要使用 knife4j ,Spring Doc 的配置中需要添加分组配置,我们这里添加一个最简单的分组配置。

com.yygnb.demo.config.SpringDocConfig

@RequiredArgsConstructor
@Configuration
public class SpringDocConfig {

    private final DocInfo docInfo;

    @Bean
    public OpenAPI heroOpenAPI() {
        return new OpenAPI()
                .info(new Info().title(docInfo.getTitle())
                        .description(docInfo.getDescription())
                        .version(docInfo.getVersion()))
                .externalDocs(new ExternalDocumentation().description(docInfo.getWebsiteName())
                        .url(docInfo.getWebsiteUrl()));
    }

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group(docInfo.getTitle())
                .pathsToMatch("/**")
                .build();
    }
}

如果不添加这个 GroupedOpenApi 实例,knife4j ui就显示不出来。

在 pom.xml 中引入 knife4j

<properties>
...
    <knife4j-springdoc-ui.version>3.0.3</knife4j-springdoc-ui.version>
</properties>

<dependencies>
...
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-springdoc-ui</artifactId>
        <version>${knife4j-springdoc-ui.version}</version>
    </dependency>
</dependencies>

启动服务,访问:

http://localhost:9099/doc.html

显示 knife4j 的ui:


今日优雅哥(工\/youyacoder)学习结束,期待关注留言分享~~

有关集成 Spring Doc 接口文档和 knife4j-SpringBoot 2.7.2 实战基础的更多相关文章

  1. springboot定时任务 - 2

    如果您希望在Spring中启用定时任务功能,则需要在主类上添加 @EnableScheduling 注解。这样Spring才会扫描 @Scheduled 注解并执行定时任务。在大多数情况下,只需要在主类上添加 @EnableScheduling 注解即可,不需要在Service层或其他类中再次添加。以下是一个示例,演示如何在SpringBoot中启用定时任务功能:@SpringBootApplication@EnableSchedulingpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.ru

  2. 基于SpringBoot的线上日志阅读器 - 2

    软件特点部署后能通过浏览器查看线上日志。支持Linux、Windows服务器。采用随机读取的方式,支持大文件的读取。支持实时打印新增的日志(类终端)。支持日志搜索。使用手册基本页面配置路径配置日志所在的目录,配置后按回车键生效,下拉框选择日志名称。选择日志后点击生效,即可加载日志。windows路径E:\java\project\log-view\logslinux路径/usr/local/XX历史模式历史模式下,不会读取新增的日志。针对历史文件可以分页读取,配置分页大小、跳转。历史模式下,支持根据关键词搜索。目前搜索引擎使用的是jdk自带类库,搜索速度相对较低,优点是比较简单。2G日志全文搜

  3. springboot使用validator进行参数校验 - 2

    1.依赖导入org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-validation2.validation常用注解@Null被注释的元素必须为null@NotNull被注释的元素不能为null,可以为空字符串@AssertTrue被注释的元素必须为true@AssertFalse被注释的元素必须为false@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@D

  4. ruby - 是否有 Log4J for Ruby 的等价物,Log4Ruby? - 2

    找了一圈也没找到。是否有Ruby的Log4X等价物?如果不是,那么处理所有调试语句的最佳方法是什么。我是Ruby的新手。谢谢! 最佳答案 Ruby带有一个内置的日志库,但是有log4r.内置库的一个简短示例:#!/usr/bin/envrubyrequire'logger'log=Logger.new('mylog.txt')log.debug"Hellolog" 关于ruby-是否有Log4JforRuby的等价物,Log4Ruby?,我们在StackOverflow上找到一个类似的问

  5. 停车系统源码-基于springboot+uniapp开源项目 - 2

    Iparking停车收费管理系统-可商用介绍Iparking是一款基于springBoot的停车收费管理系统,支持封闭车场和路边车场,支持微信支付宝多种支付渠道,支持多种硬件,涵盖了停车场管理系统的所有基础功能。技术栈Springboot,MybatisPlus,Beetl,Mysql,Redis,RabbitMQ,UniApp功能云端功能序号模块功能描述1系统管理菜单管理配置系统菜单2系统管理组织管理管理组织机构3系统管理角色管理配置系统角色,包含数据权限和功能权限配置4系统管理用户管理管理后台用户5系统管理租户管理多租户管理6系统管理公众号配置租户公众号配置7系统管理操作日志审计日志8系统

  6. ruby - 使用 Knife 更新 Chef 中的运行列表 - 2

    我有一本包含Recipe列表的Recipe。在chefknife中使用命令行工具从Recipe中添加一些特定Recipe(不是全部)的命令是什么?我知道将整个Recipe添加到运行列表的命令是knifenoderun_listaddservernamerecipe[cookbookname]。 最佳答案 所以你的想法是对的,knifenoderun_listadd$nodename$item就是你想要的命令。recipe[mycookbook]没有添加“整个Recipe”,而只是recipe[mycookbook::default]

  7. ruby-on-rails - neo4j 的哪个 Ruby REST API 客户端? - 2

    我想知道Ruby(不是JRuby,所以native绑定(bind)不是一个选项)可以使用哪些RESTAPI客户端?理想情况下,我希望API类似于neo4jgem或ActiveRecord(验证、迁移、观察者等)。当前可用的(REST)工具甚至无法与我们所拥有的相提并论,例如,在ActiveRecrod中:neograhy-只是普通RESTAPI。与模型等无关neology-只是对新地理学的包装,并不是功能齐全的ActiveModel。architect4r-符合ActiveModel,但仅提供一种查询数据的方式(Cypher语言),也不支持索引。我更喜欢architect4r的代码(主

  8. 优化大数据量查询方案——SpringBoot(Cloud)整合ES - 2

    一、Elasticsearch简介实际业务场景中,多端的查询功能都有很大的优化空间。常见的处理方式有:建索引、建物化视图简化查询逻辑、DB层之上建立缓存、分页…然而随着业务数据量的不断增多,总有那么一张表或一个业务,是无法通过常规的处理方式来缩短查询时间的。在查询功能优化上,作为开发人员应该站在公司的角度,本着优化客户体验的目的去寻找解决方案。本人有幸做过Tomcat整合solr,今天一起研究一下当前比较火热的Elasticsearch搜索引擎。Elasticsearch是一个非常强大的搜索引擎。它目前被广泛地使用于各个IT公司。Elasticsearch是由Elastic公司创建。它的代码位

  9. Neo4j 实战(一)-- Mac neo4j 安装与配置 - 2

     前言        Neo4j是一个高性能的,Nosql图形数据库。Nosql=nosql,即与传统的将数据结构化并存储在表中的数据库不一样。Neo4j将数据存储在网络上,我们也可以把Neo4j视为一个图引擎。我们打交道的是一个面对对象的、灵活的网络结构而不是严格的、静态的表。传统关系型数据库,当数据量很大时,查询性能会明显受影响,尤其是一度以上的查询。但是图形数据库却在这方面表现得很好。neo4j支持多种主流编程语言,包括.Net、Java、JavaScript、Python。本文主要是涉及到jdk和neo4j安装和适配。        注意事项:neo4j安装版本与JDK版本需要对应,不

  10. SpringBoot+Netty实现TCP客户端实现接收数据按照16进制解析并存储到Mysql以及Netty断线重连检测与自动重连 - 2

    场景在SpringBoot项目中需要对接三方系统,对接协议是TCP,需实现一个TCP客户端接收服务端发送的数据并按照16进制进行解析数据,然后对数据进行过滤,将指定类型的数据通过mybatis存储进mysql数据库中。并且当tcp服务端断连时,tcp客户端能定时检测并发起重连。全流程效果 注:博客:霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主实现1、SpringBoot+Netty实现TCP客户端本篇参考如下博客,在如下博客基础上进行修改Springboot+Netty搭建基于TCP协议的客户端(二):https://www.cnblogs.com/haolb

随机推荐