Spring Boot 整合 springdoc-openapi

2023-11-17

open api 简介

OpenApi是一个业界的 api 文档标准,一个规范。

好比java里面一个抽象的概念,即是一个抽象类,只是提供了一个api文档规范的抽象方法。

该方法目前被两大非官方实现了,一个是springfox,另一个是springdoc。

swagger 简介

swagger 是一个 api 文档维护组织,后来成为了 Open API 标准的主要定义者,现在最新的版本为17年发布的 Swagger3(Open Api3)。

springdoc 简介

SpringDoc也是 spring 社区维护的一个项目(非官方),帮助使用者将 swagger3 集成到 Spring 中。也是用来在 Spring 中帮助开发者生成文档,并可以轻松的在spring boot中使用。

该组织下的项目支持swagger页面Oauth2登录(Open API3的内容),相较 Springfox 来说,它的支撑时间更长,无疑是更好的选择。

springdoc-openapi的工作原理是在运行时检查应用程序,根据spring配置、类结构和各种注释推断API语义。自动生成JSON/YAML和HTML格式api中的文档。这个文档可以通过使用swaggerapi注释的注释来完成。

springdoc-openapi库支持:

  • OpenAPI 3
  • Spring-boot (v1 and v2)
  • JSR-303,专门用于@NotNull、@Min、@Max和@Size。 Swagger-ui
  • OAuth 2

整合使用

Maven项目中引入springdoc-openapi-ui依赖:

   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.4.3</version>
   </dependency>

springfox和springdoc注解映射关系:

@Api -> @Tag
@ApiIgnore -> @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
@ApiImplicitParam -> @Parameter
@ApiImplicitParams -> @Parameters
@ApiModel -> @Schema
@ApiModelProperty(hidden = true) -> @Schema(accessMode = READ_ONLY)
@ApiModelProperty -> @Schema
@ApiOperation(value = "foo", notes = "bar") -> @Operation(summary = "foo", description = "bar")
@ApiParam -> @Parameter
@ApiResponse(code = 404, message = "foo") -> @ApiResponse(responseCode = "404", description = "foo")

application.yml配置文件参考:

spring:
  application:
    name: springdoc-openapi
server:
  port: 8080

# ===== SpringDoc配置 =====#
springdoc:
  swagger-ui:
    # 自定义的文档界面访问路径。默认访问路径是/swagger-ui.html
    path: /springdoc/docs.html

    # 字符串类型,一共三个值来控制操作和标记的默认展开设置。它可以是“list”(仅展开标记)、“full”(展开标记和操作)或“none”(不展开任何内容)。
    docExpansion: none

    # 布尔值。控制“试用”请求的请求持续时间(毫秒)的显示。
    displayRequestDuration: true

    # 布尔值。控制供应商扩展(x-)字段和操作、参数和架构值的显示。
    showExtensions: true

    # 布尔值。控制参数的扩展名(pattern、maxLength、minLength、maximum、minminimum)字段和值的显示。
    showCommonExtensions: true

    # 布尔值。禁用swagger用户界面默认petstore url。(从v1.4.1开始提供)。
    disable-swagger-default-url: true

  api-docs:
    # enabled the /v3/api-docs endpoint
    enabled: true

    # 自定义的文档api元数据访问路径。默认访问路径是/v3/api-docs
    path: /springdoc/api-docs

    # 布尔值。在@Schema(名称name、标题title和说明description,三个属性)上启用属性解析程序。
    resolve-schema-properties: true

  # 布尔值。实现OpenApi规范的打印。
  writer-with-default-pretty-printer: true

# ===== swagger配置 =====#
swagger:
  application-name: ${spring.application.name}
  application-version: 1.0
  application-description: springdoc openapi整合Demo
  try-host: http://localhost:${server.port}

swagger配置类:

@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {
    /**
     * 项目应用名
     */
    private String applicationName;

    /**
     * 项目版本信息
     */
    private String applicationVersion;

    /**
     * 项目描述信息
     */
    private String applicationDescription;

    /**
     * 接口调试地址
     */
    private String tryHost;

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getApplicationVersion() {
        return applicationVersion;
    }

    public void setApplicationVersion(String applicationVersion) {
        this.applicationVersion = applicationVersion;
    }

    public String getApplicationDescription() {
        return applicationDescription;
    }

    public void setApplicationDescription(String applicationDescription) {
        this.applicationDescription = applicationDescription;
    }

    public String getTryHost() {
        return tryHost;
    }

    public void setTryHost(String tryHost) {
        this.tryHost = tryHost;
    }
}

一个完整详细的springdoc openapi配置示例:

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.HeaderParameter;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class SpringdocOpenapiConfiguration implements WebMvcConfigurer {

    private final SwaggerProperties swaggerProperties;

    public SpringdocOpenapiConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public OpenAPI springDocOpenAPI() {
        //配置认证、请求头参数
        Components components = new Components();
        Map<String, Object> myHeader2extensions = new HashMap<>(2);
        myHeader2extensions.put("name", "myHeader2");
        components
                .addSecuritySchemes("bearer-key", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))
                .addSecuritySchemes("basicScheme", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
                .addParameters("myHeader1", new Parameter().in("header").schema(new StringSchema()).name("myHeader1"))
                //注:这种方式有问题,不推荐
                .addHeaders("myHeader2", new Header().description("myHeader2 header").schema(new StringSchema()).extensions(myHeader2extensions))
                .addParameters("myGlobalHeader", new HeaderParameter().required(true).name("My-Global-Header").description("My Global Header").schema(new StringSchema()).required(false))
        ;

        // 接口调试路径
        Server tryServer = new Server();
        tryServer.setUrl(swaggerProperties.getTryHost());

        return new OpenAPI()
                .components(components)
                .servers(Collections.singletonList(tryServer))
                .info(new Info()
                        .title(swaggerProperties.getApplicationName() + " Api Doc")
                        .description(swaggerProperties.getApplicationDescription())
                        .version("Application Version: " + swaggerProperties.getApplicationVersion() + "\n Spring Boot Version: " + SpringBootVersion.getVersion())
                        .license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0.html"))
                )
                .externalDocs(new ExternalDocumentation()
                        .description("SpringDoc Full Documentation")
                        .url("https://springdoc.org/")
                );
    }

    /**
     * 添加全局的请求头参数
     */
    @Bean
    public OpenApiCustomiser customerGlobalHeaderOpenApiCustomiser() {
        return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
                .forEach(operation -> {
                    operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myGlobalHeader"));
                });
    }

    /**
     * 通用拦截器排除设置,所有拦截器都会自动加springdoc-opapi相关的资源排除信息,不用在应用程序自身拦截器定义的地方去添加,算是良心解耦实现。
     */
    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        try {
            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) {
                for (InterceptorRegistration interceptorRegistration : registrations) {
                    interceptorRegistration.excludePathPatterns("/springdoc**/**");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

示例

项目Demo:springdoc-openapi

效果图:

example
example

参考

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot 整合 springdoc-openapi 的相关文章

  • Spring Boot 接入支付宝完整流程实战

    1 将支付宝开放平台里下载的3个证书放在resources下面 2 写支付宝支付的配置文件 alipay properties alipay appId 你的应用id alipay serverUrl https openapi alipa
  • Spring系列之spring中编程式事务怎么用的?

    本文内容 详解spring中编程式事务的使用 spring中使用事务的2种方式 spring使事务操作变的异常容易了 spring中控制事务主要有2种方式 编程式事务 硬编码的方式 声明式事务 大家比较熟悉的注解 Transaction的方
  • IDEA工具实用开发快捷键

    选中new ArrayList lt gt 或者光标放在new前面 按ctrl alt v 选中new ArrayList lt gt 或者光标放在new后边面 按ctrl alt 空格 ideal 工具没识别maven项目的话 右键pom
  • SpringBoot原理概述

    文章目录 一 SpringBoot概述 二 运行原理剖析 1 核心运行原理 Pom xml 主启动类 2 构造流程分析 3 运行流程分析 三 配置与使用 1 配置文件 2 自动配置原理 四 趣味练习 自定义starter 一 SpringB
  • idea新建一个Spring项目(最基础)

    首先 笼统介绍一下 什么是spring 1 Spring 的主要作用就是为代码 解耦 降低代码间的耦合度 根据功能的不同 可以将一个系统中的代码分为主业务逻辑与系统级业务逻辑两类 它们各自具有鲜明的特点 主业务代码间逻辑联系紧密 有具体的专
  • SpringBoot2.x 集成 Swagger3(springdoc-openapi)

    Swagger是一款RESTFUL接口的文档在线自动生成加功能测试的软件 提供描述 生产 消费和可视化RESTful Web Service Swagger也是一个api文档维护组织 后来成为了OpenAPI 一个业界的api文档标准 标准
  • 微服务架构中的身份验证问题 :JSON Web Tokens( JWT)

    本文翻译自 http www svlada com jwt token authentication with spring boot 场景介绍 软件安全是一件很负责的问题 由于微服务系统中每个服务都要处理安全问题 所以在微服务场景下会更加
  • Spring系列之深入理解java注解及spring对注解的增强(预备知识)

    最近有个朋友去阿里面试 被面试官来了个灵魂拷问 注解是干什么的 一个注解可以使用多次么 如何使用 Inherited是做什么的 Target中的 TYPE PARAMETER和TYPE USER 用在什么地方 泛型中如何使用注解 注解定义可
  • 注解@Autowired是如何实现的

    1 Autowired注解用法 2 Autowired注解的作用到底是什么 Autowired这个注解我们经常在使用 现在 我想问的是 它的作用到底是什么呢 首先 我们从所属范围来看 事实上这个注解是属于spring的容器配置的一个注解 与
  • spring boot 数据库层

    项目开启 首先设计数据库以及存储表 表的联系 需要存贮的信息 基本表的性质 基本表与中间表 临时表不同 因为它具有如下四个特性 1 原子性 基本表中的字段是不可再分解的 2 原始性 基本表中的记录是原始数据 基础数据 的记录 3 演绎性 由
  • Spring系列之缓存使用(@EnableCaching、@Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig)

    本文主要详解spring中缓存的使用 背景 缓存大家都有了解过吧 主要用来提升系统查询速度 比如电商中商品详情信息 这些信息通常不会经常变动但是会高频访问 我们可以将这些信息从db中拿出来放在缓存中 比如redis中 本地内存中 当获取的时
  • Spring初识

    文章目录 Spring框架 一 Spring简介 一 Spring的介绍及需要的依赖 二 Spring的优点 二 Spring的组成及拓展 一 什么是Spring Boot 二 什么是Spring Cloud 三 IOC 控制反转 一 IO
  • JavaWeb的项目设计思路

    JavaWeb在做项目的时候 最重要的是应用了分层操作的思想 JavaBean JSP Servlet 就是Model View Controller 即MVC的设计模式 entity 实体类 和数据库中一一对应 表名 类名 字段 属性 D
  • Spring系列之@Aspect中5中通知详解

    Aspect中有5种通知 Before 前置通知 在方法执行之前执行 Aroud 环绕通知 围绕着方法执行 After 后置通知 在方法执行之后执行 AfterReturning 返回通知 在方法返回结果之后执行 AfterThrowing
  • Spring系列之@Value【用法、数据来源、动态刷新】

    面试官 Spring中的 Value用过么 介绍一下 我 Value可以标注在字段上面 可以将外部配置文件中的数据 比如可以将数据库的一些配置信息放在配置文件中 然后通过 Value的方式将其注入到bean的一些字段中 面试官 那就是说 V
  • Spring系列之BeanFactory扩展(BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor)

    先来看几个问题 BeanFactoryPostProcessor是做什么的 BeanDefinitionRegistryPostProcessor是干什么的 BeanFactoryPostProcessor和BeanDefinitionRe
  • nginx 代理后面的 SpringDoc/Swagger

    我们正在运行一个服务nginx代理以便 http service post 8080 swagger ui html被路由到公共地址https host com services post swagger ui html 或者从另一种方式定
  • SpringDoc - 如何以编程方式添加模式

    我正在使用 SpringDoc 并尝试以编程方式向 OpenApi 添加架构 但没有成功 Bean public OpenAPI customOpenAPI Schema mySchema new Schema mySchema type
  • spring boot swagger 3“无法加载远程配置。”

    Spring Boot 2 6 3 与 Springdoc
  • 使用/从 Springfox 迁移到 springdoc-openapi 有什么优势吗?

    为了在 SpringBoot 2 7 中启用 Swagger 选择 springdoc openapi 相对于 Springfox 的优点 缺点是什么 这可能被认为是基于意见的 但实际上有事实支持使用 springdoc 而不是 Sprin

随机推荐

  • 一起聊聊等保测评

    现在好多企业里面好像都在搞这个等保测评 这个等保测评终究是个什么东西呢 那企业为什么要做这个等保测评呢 做完之后对企业又有什么帮助呢 然后就是哪些企业需要做等保测呢 甚至很多企业做了很多次等保测评最后都不太了解这个等保测评 那今天就让我们一
  • QFramelessWidget 中多个组件添加滚动条

    QFramelessWidget 无边框窗口 QFramelessWidget是一个无框架的窗口小部件 它提供了一种在主窗口外绘制自定义窗口小部件的方法 在QFramelessWidget中添加多个组件时 有时候需要在这些组件中添加滚动条
  • echarts仪表盘进度条、指针动态渐变色显示

    1 echarts仪表盘实现效果如下 2 配置项代码 const option 鼠标悬浮的提示 tooltip formatter b c series type gauge min 0 最大值 max 100 最小值 startAngle
  • shiro简介以及基本框架搭建

    Shiro框架是一个基于java实现认证登录的安全框架 它是由Apache推出的 目前最新的版本是1 3 2版本 Shiro主要的功能有 Authentication 身份认证 登录 Authorization 授权 Session Man
  • ftp虚拟服务器登录,ftp虚拟服务器登录

    ftp虚拟服务器登录 内容精选 换一换 默认部署在VPC下的应用可以调用API 如果域名解析失败 则参考配置内网DNS 在当前终端节点上配置DNS服务器 配置完成后 部署在VPC下的应用可以调用API 配置DNS需要配置 etc 目录下的r
  • c++---优先队列(priority_queue)

    C 中的优先队列是STL中的派生容器 它仅考虑最高优先级元素 队列遵循FIFO策略 而优先队列根据优先级弹出元素 即 优先级最高的元素首先弹出 与普通队列区别 在优先队列中 队列中的每个元素都与某个优先级相关联 但是优先级在队列数据结构中不
  • postman做接口测试时一些实用的操作

    Postman 之前是作为Chrome 的一个插件 现在要下载应用才能使用 以下是postman 的界面 各个功能区的使用如下 快捷区 快捷区提供常用的操作入口 包括运行收藏夹的一组测试数据 导入别人共享的收藏夹测试数据 Import fr
  • flutter1.12版本android适配

    1 修改MainActivity public class MainActivity extends io flutter embedding android FlutterActivity 如果与flutter有通信 则覆盖下面方法 pr
  • Makefile的$@、$%、$?、$^ 、$+、$*自动化变量说明

    自动变量 含义 表示规则中的目标文件集 在模式规则中 如果有多个目标 那么 就是匹配于目标中模式定义的集合 仅当目标是函数库文件时 表示规则中的目标成员名 例如 如果一个目标是 foo a bar o 那么 就是 bar o 就是 foo
  • 项目五:智慧家庭

    目录 1 项目功能演示 2 总体框架 3 WIFI连接模块 4 智能门禁模块 5 数据采集模块 6 智能检测模块
  • Caffe源码(十一):io.cpp 分析

    目录 目录 简单介绍 主要函数 ReadProtoFromTextFile 函数 WriteProtoToTextFile 函数 ReadProtoFromBinaryFile 函数 WriteProtoToBinaryFile 函数 Re
  • 关于传递list类型的参数的问题

    java中除了基础的数据类型是值传递外 其它类型都是对象 也就是引用类型 地址传递 这个就不多说了 今天遇到一个问题 就是在多次添加同一个list对象到另一个list里的时候 为什么会添加多少次list对象 外面这层list的大小就有多少呢
  • vim 基础操作

    bash或cmd 已经配置好vim的环境变量 下 vim a txt 创建a txt文件 vim 下 i a o O s进入插入 编辑 模式 esc 退出插入模式 回到正常模式 正常模式下 x 或 wq 保存退出vim 称为底行模式 在正常
  • java项目部署到阿里云服务器步骤

    阿里云服务器详细步骤 一 什么是云服务器ECS 是阿里云产品体系中 最基础的计算服务 通常用作应用程序的运行环境 最重要的特点是弹性 二 基础运行环境 用户的应用程序运行在实例的操作系统上 三 特点 弹性 容量不够可以直接在云服务器上扩展配
  • vue3 中如何动态加载本地图片资源

    在untils文件中加入getImageUrl方法 export const getImageUrl name string type string png gt return new URL 本地资源路径 src assets image
  • @Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig详解

    文章目录 一 概述 二 缓存注解种类 三 优劣势说明 四 如何使用 五 详细介绍介绍 1 Cacheable 常用 1 value cacheNames 属性 2 key属性 3 keyGenerator 属性 4 cacheManager
  • java判断两个list是否有交集_java怎么判断两个集合之间是否有交集

    背景 前端传了list集合 后端字段里存的也是 1 2 3 4 这种形式 不借助sql 怎么看前端传的集合是否在后端字段的集合中 代码 public static boolean judgeIntersection List list1 L
  • ipv4服务器修改,更改手动IP地址方法.pdf

    更改手动 IP 地址方法 1 点击显示器右下角的 无线信号标志 点击打开网络和共享 点击无线网络连接 点击详细信息查看现在的 IP 地址 IPv4 地址 192 168 1 103 IPv4 子网掩码 255 255 255 0 IPv4
  • go 问题合集(持续更新)

    数据库单复数问题 默认使用go的话 查询数据库对应的表单是在你的结构体上 s 变成复数操作 但是我们一般不习惯这样子建表 所以在构建db的时候 加上 singulartable ture 2 导入不了本地的包 看 那个目录的package是
  • Spring Boot 整合 springdoc-openapi

    springdoc openapi官网 springdoc org springdoc openapi Github仓库 springdoc springdoc openapi springdoc openapi Maven仓库 Home