当前位置: 首页 > article >正文

SpringBoot之如何集成SpringDoc最详细文档

文章目录

  • 一、概念解释
    • 1、OpenAPI
    • 2、Swagger
    • 3、Springfox
    • 4、Springdoc
    • 5. 关系与区别
  • 二、SpringDoc基本使用
    • 1、导包
    • 2、正常编写代码,不需要任何注解
    • 3、运行后访问下面的链接即可
  • 三、SpringDoc进阶使用
    • 1、配置文档信息
    • 2、配置文档分组
    • 3、springdoc的配置参数
      • **1. 基础配置**
        • **API 文档路径-springdoc.api-docs.path**
        • **Swagger UI 路径-springdoc.swagger-ui.path**
        • **是否启用 API 文档-springdoc.api-docs.enabled**
        • **是否启用 Swagger UI-springdoc.swagger-ui.enabled**
      • **2. 全局元信息-info**
        • **应用标题-springdoc.info.title**
        • **应用描述-springdoc.info.description**
        • **版本号-pringdoc.info.version**
        • **联系人信息-springdoc.info.contact**
        • **许可信息-pringdoc.info.license**
      • **3. 分组与模块化**
        • **分组支持-springdoc.group-configs**
        • **扫描包范围-springdoc.packages-to-scan**
        • **排除特定路径-springdoc.paths-to-exclude**
      • **4. 安全配置**
        • **全局安全方案**
        • **全局安全要求**
      • **5. 自定义行为**
        • **缓存控制**
        • **排序规则**
        • **服务器地址-pringdoc.servers**
      • **6. 高级配置**
        • **自定义 OpenAPI 对象**
        • **自定义 Swagger UI**
      • **7. 总结**
    • 4、SpringDoc注解
      • **1. 核心注解**
        • **@Tag**
      • **2. 方法级别注解**
        • **@Operation**
        • **@ApiResponse 和 @ApiResponses**
      • **3. 参数相关注解**
        • **@Parameter**
        • **@Parameters**
      • **4. 实体模型相关注解**
        • **@Schema**
      • **5. 其他注解**
        • **@Hidden**
      • **6. 配置相关注解(不常用)**
        • **@OpenAPIDefinition**
      • **7. 总结**
  • 四、在实际项目上如何使用
    • 1、导包
    • 2、写配置类
      • 1)、配置实体类
      • 2)、配置类
    • 3、编写配置参数

系列文章:
springboot-swagger详解
springboot-优美的Knife4j文档-Swagger进化
Spring Cloud Gateway 网关整合 Knife4j
SpringBoot之如何集成SpringDoc最详细文档

一、概念解释

Swagger和Springdoc是两个常用的工具,用于生成和维护API文档,特别是针对基于REST的Web服务。它们有效地提升了API的可读性和可维护性,帮助开发者、产品经理和其他利益相关者更好地理解和使用所提供的API。

谈到API文档,那就绕不开大名鼎鼎的Swagger,但是你是否还听说过:OpenAPI,Springfox,Springdoc?你第一次看到这些脑瓜子是不是嗡嗡的?

1、OpenAPI

OpenApi 就像 JDBC 一样,制定了各种各样的规范,而 Swagger 和 SpringDoc 则类似于各种各样的数据库驱动,是具体的实现

  • 定义 :OpenAPI 是一个开放标准,用于描述 RESTful API 的接口规范。它最初由 Swagger 项目发展而来,后来成为独立的标准(目前由 OpenAPI Initiative 维护)。

  • 版本 :

    • OpenAPI 2.0 :基于 Swagger 2.0 规范。
    • OpenAPI 3.0+ :是更新的版本,引入了许多新特性(如增强的请求体描述、组件复用等)。
  • 作用 :提供一种标准化的方式来描述 API 的结构、路径、参数、响应等内容,便于开发者和工具生成文档、测试接口。

2、Swagger

它是SmartBear这个公司的一个开源项目,里面提供了一系列工具,包括著名的 swagger-ui。
swagger是早于OpenApi的,某一天swagger将自己的API设计贡献给了OpenApi,然后由其标准化了。

  • 定义 :Swagger 是一组围绕 OpenAPI 标准构建的工具集,包括代码生成器、UI 展示工具等。
  • 版本 :
    • Swagger 2.x :基于 OpenAPI 2.0,是最广泛使用的版本之一。
    • Swagger 3.x :基于 OpenAPI 3.0+,支持更复杂的 API 描述功能。
  • 工具 :
    • Swagger UI :为 OpenAPI 文档提供交互式界面,方便开发者测试 API。
    • Swagger Codegen :根据 OpenAPI 文档生成客户端代码或服务器端框架代码。

3、Springfox

是Spring生态的一个开源库,是Swagger与OpenApi规范的具体实现。我们使用它就可以在spring中生成API文档。以前基本上是行业标准,目前最新版本可以支持 Swagger2, Swagger3 以及 OpenAPI3 三种格式。但是其从 2020年7月14号就不再更新了,不支持springboot3,所以业界都在不断的转向我们今天要谈论的另一个库Springdoc,新项目就不要用了。

  • 定义 :Springfox 是一个专门为 Spring 框架设计的库,用于自动生成基于 Swagger/OpenAPI 的 API 文档。
  • 特点 :
    • 支持 Spring MVC 和 Spring Boot。
    • 主要基于 Swagger 2.x 和 OpenAPI 2.0 。
    • 通过注解(如 @Api、@ApiOperation 等)来描述 API。
  • 局限性 :
    • 对 OpenAPI 3.0 的支持较弱(尽管有实验性支持,但不够完善)。
    • 在 Spring Boot 2.6 及更高版本中,由于兼容性问题(如路径匹配策略的变化),Springfox 的使用变得复杂甚至不可行。

4、Springdoc

算是后起之秀,带着继任Springfox的使命而来。其支持OpenApi规范,支持Springboot3,我们的新项目都应该使用这个。

  • 定义 :Springdoc 是一个现代化的开源库,专为 Spring Boot 应用程序设计,用于自动生成基于 OpenAPI 3.0+ 的 API 文档。
  • 特点 :
    • 原生支持 OpenAPI 3.0+ ,并提供对 Spring Boot 2.6+ 的良好兼容性。
    • 使用标准的 OpenAPI 注解(如 @Operation、@Parameter 等),而不是 Swagger 特有的注解。
    • 提供内置的 Swagger UI,方便开发者快速查看和测试 API。
  • 优势 :
    • 更轻量、更易配置。
    • 更好的性能和兼容性。
    • 社区活跃,更新频繁。

SpringDoc 支持:

  • OpenAPI 3
  • Spring-boot,全版本都支持。
  • JSR-303 中提供的一些注解,例如 @NotNull、@Min、@Max 以及 @Size 等。
  • Swagger-ui:SpringDoc 提供的接口 JSON 也可以通过 Swagger-ui 展示出来。
  • OAuth 2

5. 关系与区别

特性SpringfoxSpringdocSwaggerOpenAPI
主要用途自动生成 API 文档自动生成 API 文档工具集,用于生成文档和测试 APIAPI 描述标准
支持的规范Swagger 2.x / OpenAPI 2.0OpenAPI 3.0+Swagger 2.x / Swagger 3.xOpenAPI 2.0 / OpenAPI 3.0+
Spring Boot 兼容性较差(尤其是 2.6+ 版本)良好不直接相关不直接相关
注解使用 Swagger 特定注解(如 @Api使用 OpenAPI 标准注解(如 @Operation使用 Swagger 特定注解定义了标准注解
工具支持提供 Swagger UI提供 Swagger UI提供 Swagger UI 和 Codegen无直接工具支持,需依赖实现(如 Swagger)
社区活跃度逐渐减少

二、SpringDoc基本使用

我们可以在springboot中使用SpringDoc来生成API文档,详情可以参考官网,下面我们来简单的实践一下。

1、导包

在springboot中使用springdoc起步非常容易,只需要引入其starter即可

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.7.0</version> <!-- 版本可替换 -->
</dependency>

2、正常编写代码,不需要任何注解

在这里插入图片描述

3、运行后访问下面的链接即可

http://server:port/context-path/swagger-ui.html

例如:

http://localhost:9204/swagger-ui.html
在这里插入图片描述

三、SpringDoc进阶使用

虽然上边配置的SpringDoc很好用,但是对比swagger我们就知道,缺少了很多信息,当然springdoc的集成不可能就这点东西,不然也没有这篇文章了。

1、配置文档信息

得益于springboot的强大,我们只需添加一个依赖就可以使用API文档了,但是使用的都是默认值,我们当然也希望对其进行各种自定义的配置

创建一个OpenAPI 的bean,配置文档名称等信息

package com.wenge.business.config;

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

/**
 * Swagger 文档配置
 *
 * @author wkl
 */
@Configuration
public class SpringDocAutoConfiguration {
    @Bean
    public OpenAPI openApi() {

        return new OpenAPI()
                .info(new Info()
                        .title("这是标题")
                        .description("这是备注")
                        .version("这是版本")
                        .license(new License()
                                .name("这是许可证")
                                .url("这是许可证链接"))
                        .contact(new Contact()
                                .name("这是作者")
                                .url("这是作者链接")
                                .email("这是作者email"))
                );
    }
}

在这里插入图片描述

2、配置文档分组

用来配置分组的,假如你有多类controller一类以/tacticsInfo为前缀分组,一类以/admin为前缀,就可以将其配置为两个分组。很多时候我们只有一个分组,所以就不需要下面的配置。

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("tacticsInfo")
                .pathsToMatch("/tacticsInfo/**")//以/tacticsInfo开头的的api都进这个分组
                .build();
    }

    @Bean
    public GroupedOpenApi otherApi() {
        return GroupedOpenApi.builder()
                .group("other")
                .pathsToMatch("/admin/**")//以/tacticsInfo开头的的api都进这个分组
                .build();
    }

//    @Bean
//    public GroupedOpenApi otherApi() {
//        return GroupedOpenApi.builder()
//                .group("other")
//                .pathsToMatch("/**/**")//这样配置,那就是所有的api都进这个分组
//                .build();
//    }

可以通过右上角的下拉框选择要展示的group。
在这里插入图片描述

3、springdoc的配置参数

1. 基础配置

API 文档路径-springdoc.api-docs.path
  • springdoc.api-docs.path
    • 作用:指定 OpenAPI JSON 文档的访问路径。
    • 默认值/v3/api-docs
    • 示例
      springdoc.api-docs.path=/openapi
      
Swagger UI 路径-springdoc.swagger-ui.path
  • springdoc.swagger-ui.path
    • 作用:指定 Swagger UI 的访问路径。
    • 默认值/swagger-ui.html
    • 示例
      springdoc.swagger-ui.path=/docs
      
是否启用 API 文档-springdoc.api-docs.enabled
  • springdoc.api-docs.enabled
    • 作用:启用或禁用 OpenAPI 文档生成功能。
    • 默认值true
    • 示例
      springdoc.api-docs.enabled=false
      
是否启用 Swagger UI-springdoc.swagger-ui.enabled
  • springdoc.swagger-ui.enabled
    • 作用:启用或禁用 Swagger UI。
    • 默认值true
    • 示例
      springdoc.swagger-ui.enabled=false
      

2. 全局元信息-info

应用标题-springdoc.info.title
  • springdoc.info.title
    • 作用:设置 API 文档的标题。
    • 默认值:空
    • 示例
      springdoc.info.title=用户管理系统
      
应用描述-springdoc.info.description
  • springdoc.info.description
    • 作用:设置 API 文档的描述信息。
    • 默认值:空
    • 示例
      springdoc.info.description=用户管理相关的 API 文档
      
版本号-pringdoc.info.version
  • springdoc.info.version
    • 作用:设置 API 文档的版本号。
    • 默认值:空
    • 示例
      springdoc.info.version=1.0.0
      
联系人信息-springdoc.info.contact
  • springdoc.info.contact.name
  • springdoc.info.contact.email
  • springdoc.info.contact.url
    • 作用:设置文档的联系人信息(姓名、邮箱、URL)。
    • 默认值:空
    • 示例
      springdoc.info.contact.name=John Doe
      springdoc.info.contact.email=john.doe@example.com
      springdoc.info.contact.url=http://example.com
      
许可信息-pringdoc.info.license
  • springdoc.info.license.name
  • springdoc.info.license.url
    • 作用:设置文档的许可证信息(名称、URL)。
    • 默认值:空
    • 示例
      springdoc.info.license.name=Apache 2.0
      springdoc.info.license.url=https://www.apache.org/licenses/LICENSE-2.0
      

3. 分组与模块化

分组支持-springdoc.group-configs
  • springdoc.group-configs
    • 作用:为不同的控制器或包生成独立的 API 文档分组。
    • 示例
      springdoc.group-configs[0].group=user-api
      springdoc.group-configs[0].packages-to-scan=com.example.user
      springdoc.group-configs[1].group=order-api
      springdoc.group-configs[1].packages-to-scan=com.example.order
      
扫描包范围-springdoc.packages-to-scan
  • springdoc.packages-to-scan
    • 作用:指定需要扫描的包范围,用于生成 API 文档。
    • 默认值:当前应用程序的所有包。
    • 示例
      springdoc.packages-to-scan=com.example.api
      
排除特定路径-springdoc.paths-to-exclude
  • springdoc.paths-to-exclude
    • 作用:排除某些路径,不将其包含在生成的 API 文档中。
    • 默认值:无
    • 示例
      springdoc.paths-to-exclude=/admin/**
      

4. 安全配置

全局安全方案
  • springdoc.api-docs.security-schemes
    • 作用:定义全局的安全方案(如 OAuth2、API Key 等)。
    • 示例
      springdoc.api-docs.security-schemes[0].name=ApiKeyAuth
      springdoc.api-docs.security-schemes[0].type=apiKey
      springdoc.api-docs.security-schemes[0].in=header
      
全局安全要求
  • springdoc.api-docs.security-requirements
    • 作用:定义全局的安全要求。
    • 示例
      springdoc.api-docs.security-requirements[0]=ApiKeyAuth
      

5. 自定义行为

缓存控制
  • springdoc.cache.disabled
    • 作用:禁用 API 文档的缓存。
    • 默认值false
    • 示例
      springdoc.cache.disabled=true
      
排序规则
  • springdoc.default-flat-param-object
    • 作用:是否将参数对象展平为单个参数。
    • 默认值false
    • 示例
      springdoc.default-flat-param-object=true
      
服务器地址-pringdoc.servers
  • springdoc.servers
    • 作用:定义 API 的服务器地址列表。
    • 示例
      springdoc.servers[0].url=http://localhost:8080
      springdoc.servers[0].description=本地开发环境
      springdoc.servers[1].url=https://api.example.com
      springdoc.servers[1].description=生产环境
      

6. 高级配置

自定义 OpenAPI 对象
  • 作用:通过 Java 配置类自定义 OpenAPI 对象。
  • 示例
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("用户管理系统")
                .version("1.0")
                .description("用户管理相关的 API 文档"))
            .addServersItem(new Server().url("http://localhost:8080").description("本地开发环境"));
    }
    
自定义 Swagger UI
  • 作用:通过 Java 配置类自定义 Swagger UI 行为。
  • 示例
    @Bean
    public SwaggerUiConfigProperties swaggerUiConfig() {
        SwaggerUiConfigProperties config = new SwaggerUiConfigProperties();
        config.setPath("/custom-docs");
        return config;
    }
    

7. 总结

以下是 springdoc 配置参数的分类总结:

类别参数作用
基础配置springdoc.api-docs.path, springdoc.swagger-ui.path, springdoc.api-docs.enabled配置 API 文档路径、Swagger UI 路径及启用状态。
全局元信息springdoc.info.title, springdoc.info.description, springdoc.info.version设置 API 文档的标题、描述、版本等基本信息。
分组与模块化springdoc.group-configs, springdoc.packages-to-scan, springdoc.paths-to-exclude支持分组、限制扫描范围、排除特定路径。
安全配置springdoc.api-docs.security-schemes, springdoc.api-docs.security-requirements定义全局安全方案和要求。
自定义行为springdoc.cache.disabled, springdoc.default-flat-param-object, springdoc.servers控制缓存、参数对象展平、服务器地址等高级功能。
高级配置自定义 OpenAPI 对象、Swagger UI 配置通过代码方式实现更灵活的定制。

4、SpringDoc注解

1. 核心注解

@Tag
  • 作用:为控制器或方法分组,便于组织和分类 API。

  • 常用属性

    • name:标签名称。
    • description:标签描述信息。
  • 示例

      @Tag(name = "策略库接口",description = "这是策略库的所有接口")
      @RestController
      @RequestMapping("/tacticsInfo")
      public class TacticsInfoController extends BaseController
      {
        // ...
       }
    

在这里插入图片描述


2. 方法级别注解

@Operation
  • 作用:描述一个 API 方法的功能。
  • 常用属性
    • summary:方法的简短描述。
    • description:方法的详细描述。
    • responses:定义可能的响应结果。
    • deprecated:标记方法是否已废弃。
  • 示例
      @Operation(summary = "查询策略库:tactics_info列表",description = "查询策略库:tactics_info列表-list接口")
      @RequiresPermissions("business:tacticsInfo:list")
      @GetMapping("/list")
      public TableDataInfo list(TacticsInfo tacticsInfo)
      {
        // ...
    }
    

在这里插入图片描述

@ApiResponse 和 @ApiResponses
  • 作用:描述 API 方法的响应结果。
  • 常用属性
    • responseCode:HTTP 状态码。
    • description:响应描述信息。
    • content:响应的内容类型(如 JSON、XML)。
  • 示例
    @Operation(summary = "创建用户", description = "根据用户信息创建新用户")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "成功创建用户"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        // ...
    }
    

3. 参数相关注解

@Parameter
  • 作用:描述方法参数的含义。
  • 常用属性
    • name:参数名称。
    • description:参数描述信息。
    • required:是否必填。
    • example:参数示例值。
    • in:参数位置(如 pathqueryheader 等)。
  • 示例
    @Operation(summary = "根据 ID 获取用户")
    @GetMapping("/{id}")
    public User getUserById(
        @Parameter(name = "id", description = "用户 ID", required = true, example = "1") 
        @PathVariable Long id) {
        // ...
    }
    
@Parameters
  • 作用:描述多个参数。
  • 示例
    @Operation(summary = "搜索用户")
    @Parameters({
        @Parameter(name = "name", description = "用户名", in = ParameterIn.QUERY),
        @Parameter(name = "age", description = "用户年龄", in = ParameterIn.QUERY)
    })
    @GetMapping("/search")
    public List<User> searchUsers(@RequestParam String name, @RequestParam Integer age) {
        // ...
    }
    

4. 实体模型相关注解

@Schema
  • 作用:描述实体类或字段的信息。
  • 常用属性
    • description:模型或字段的描述信息。
    • example:字段示例值。
    • required:字段是否必填。
    • type:字段的数据类型。
    • format:字段的格式(如 date-timeemail 等)。
  • 示例
    @Schema(description = "用户的基本信息")
    public class User {
        @Schema(description = "用户 ID", example = "1", required = true)
        private Long id;
    
        @Schema(description = "用户名", example = "John Doe", required = true)
        private String name;
    
        @Schema(description = "用户年龄", example = "25")
        private Integer age;
        // getters and setters
    }
    

5. 其他注解

@Hidden
  • 作用:隐藏某个类、方法或参数,不将其包含在生成的文档中。
  • 示例
    @Hidden
    @GetMapping("/internal")
    public String internalEndpoint() {
        return "This endpoint is ignored by springdoc.";
    }
    

6. 配置相关注解(不常用)

@OpenAPIDefinition
  • 作用:全局配置 OpenAPI 文档的元信息。这个不常用,还是常用配置文件类型的
  • 常用属性
    • info:文档的基本信息(标题、版本、描述等)。
    • tags:全局标签定义。
    • servers:API 的服务器地址。
  • 示例
    @OpenAPIDefinition(
        info = @Info(title = "用户管理系统", version = "1.0", description = "用户相关的 API 文档"),
        tags = {
            @Tag(name = "用户管理", description = "与用户相关的操作")
        },
        servers = {
            @Server(url = "http://localhost:8080", description = "本地开发环境")
        }
    )
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

7. 总结

以下是 springdoc 常用注解的分类总结:

注解作用
@Tag为控制器或方法分组,便于组织和分类 API。
@Operation描述 API 方法的功能。
@ApiResponse描述单个响应结果。
@Parameter描述方法参数的含义。
@Schema描述实体类或字段的信息。
@Hidden隐藏某个类、方法或参数,不包含在生成的文档中。
@OpenAPIDefinition全局配置 OpenAPI 文档的元信息(标题、版本、描述等)。

四、在实际项目上如何使用

1、导包

在springboot中使用springdoc起步非常容易,只需要引入其starter即可

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.7.0</version> <!-- 版本可替换 -->
</dependency>

2、写配置类

1)、配置实体类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.License;

/**
 * Swagger 配置属性
 *
 * @author wkl
 */
@ConfigurationProperties(prefix = "springdoc")
public class SpringDocProperties
{
    /**
     * 网关
     */
    private String gatewayUrl;

    /**
     * 文档基本信息
     */
    @NestedConfigurationProperty
    private InfoProperties info = new InfoProperties();

    /**
     * <p>
     * 文档的基础属性信息
     * </p>
     *
     * @see io.swagger.v3.oas.models.info.Info
     *
     * 为了 springboot 自动生产配置提示信息,所以这里复制一个类出来
     */
    public static class InfoProperties
    {
        /**
         * 标题
         */
        private String title = null;

        /**
         * 描述
         */
        private String description = null;

        /**
         * 联系人信息
         */
        @NestedConfigurationProperty
        private Contact contact = null;

        /**
         * 许可证
         */
        @NestedConfigurationProperty
        private License license = null;

        /**
         * 版本
         */
        private String version = null;

        public String getTitle()
        {
            return title;
        }

        public void setTitle(String title)
        {
            this.title = title;
        }

        public String getDescription()
        {
            return description;
        }

        public void setDescription(String description)
        {
            this.description = description;
        }

        public Contact getContact()
        {
            return contact;
        }

        public void setContact(Contact contact)
        {
            this.contact = contact;
        }

        public License getLicense()
        {
            return license;
        }

        public void setLicense(License license)
        {
            this.license = license;
        }

        public String getVersion()
        {
            return version;
        }

        public void setVersion(String version)
        {
            this.version = version;
        }
    }

    public String getGatewayUrl()
    {
        return gatewayUrl;
    }

    public void setGatewayUrl(String gatewayUrl)
    {
        this.gatewayUrl = gatewayUrl;
    }

    public InfoProperties getInfo()
    {
        return info;
    }

    public void setInfo(InfoProperties info)
    {
        this.info = info;
    }
}

2)、配置类

import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import com.wenge.common.swagger.config.properties.SpringDocProperties;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;

/**
 * Swagger 文档配置
 *
 * @author ruoyi
 */
@EnableConfigurationProperties(SpringDocProperties.class)
@ConditionalOnProperty(name = "springdoc.api-docs.enabled", havingValue = "true", matchIfMissing = true)
public class SpringDocAutoConfiguration
{
    @Bean
    @ConditionalOnMissingBean(OpenAPI.class)
    public OpenAPI openApi(SpringDocProperties properties)
    {
        return new OpenAPI().components(new Components()
            // 设置认证的请求头
            .addSecuritySchemes("apikey", securityScheme()))
            .addSecurityItem(new SecurityRequirement().addList("apikey"))
            .info(convertInfo(properties.getInfo()))
            .servers(servers(properties.getGatewayUrl()));
    }

    public SecurityScheme securityScheme()
    {
        return new SecurityScheme().type(SecurityScheme.Type.APIKEY)
            .name("Authorization")
            .in(SecurityScheme.In.HEADER)
            .scheme("Bearer");
    }

    private Info convertInfo(SpringDocProperties.InfoProperties infoProperties)
    {
        Info info = new Info();
        info.setTitle(infoProperties.getTitle());
        info.setDescription(infoProperties.getDescription());
        info.setContact(infoProperties.getContact());
        info.setLicense(infoProperties.getLicense());
        info.setVersion(infoProperties.getVersion());
        return info;
    }

    public List<Server> servers(String gatewayUrl)
    {
        List<Server> serverList = new ArrayList<>();
        serverList.add(new Server().url(gatewayUrl));
        return serverList;
    }
}

3、编写配置参数

springdoc:
  api-docs:
    path: /v3/api-docs
  swagger-ui:
    path: /swagger-ui.html
    enabled: true
    operationsSorter: method
  show-actuator: true


http://www.kler.cn/a/591348.html

相关文章:

  • Caffeine 缓存:简介、优势及应用场景
  • iwebsec-updatexml报错注入
  • 区块链 智能合约安全 | 整型溢出漏洞
  • 【2025】基于ssm+uniapp的图书馆座位预约小程序系统(源码、万字文档、图文修改、调试答疑)
  • 前端开发概论
  • Github 2025-03-17开源项目周报Top12
  • Statistical Learning 统计学习 :回归任务,线性回归,最小二乘法,标准误差,R方
  • Java面试黄金宝典2
  • 学习知识的心理和方法杂记-04
  • 强化学习(赵世钰版)-学习笔记(8.值函数方法)
  • MySQL--DDL
  • Python教学:lambda表达式的应用-由DeepSeek产生
  • 技术路线图ppt模板_流程图ppt图表_PPT架构图
  • 优选算法合集————双指针(专题四)
  • django如何配置使用asgi
  • 【LInux进程六】命令行参数和环境变量
  • 【大模型基础_毛玉仁】2.6 非 Transformer 架构
  • SSH后判断当前服务器是云主机、物理机、虚拟机、docker环境
  • 谈谈 TypeScript 中的模块系统,如何使用 ES Modules 和 CommonJS 模块?
  • STM32---FreeRTOS内存管理实验