SpringBoot3.3集成knif4j-swagger文档方式和使用案例

springboot3 集成 knif4j :

访问地址:

swagger 接口文档默认地址:http://localhost:8080/swagger-ui.html#

Knife4j 接口文档默认地址:http://127.0.0.1:8080/doc.html

Maven:

xml 复制代码
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
      <version>4.4.0</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>3.3.0</version>
     </dependency>
    
      <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-gateway-spring-boot-starter</artifactId>
        <version>${knife4j-openapi3.version}</version>
      </dependency>
    

基础微服务配置:

yml 复制代码
knife4j:
  # 开启增强配置
  enable: true
  basic:
    enable: true
    # Basic认证用户名
    username: babasic
    # Basic认证密码
    password: BaBasic123!@#plm
  ## 开启生产环境屏蔽,一定要先开启knife4j增强才会生效
  ## You do not have permission to access this page
  production: false

网关配置:

yml 复制代码
knife4j:
  gateway:
    enabled: true
    # 排序规则(tag/operation排序自4.2.0版本新增)
    # 取值:alpha-默认排序规则,官方swagger-ui默认实现,order-Knife4j提供的增强排序规则,开发者可扩展x-order,根据数值来自定义排序
    tags-sorter: order
    operations-sorter: order
    # 指定服务发现的模式聚合微服务文档
    strategy: manual
    routes:
      - name: App1服务
        # 子服务存在其他分组情况,聚合其他分组
        url: /app1/v3/api-docs
        # 服务名称(Optional)
        service-name: baian-cloud-test-app1
        # 路由前缀
        context-path: /app1
        # 排序
        order: 1
      - name: App2服务
        # 子服务存在其他分组情况,聚合其他分组
        url: /app2/v3/api-docs
        # 服务名称(Optional)
        service-name: baian-cloud-test-app2
        # 路由前缀
        context-path: /app2
        # 排序
        order: 2
      - name: App3服务
        # 子服务存在其他分组情况,聚合其他分组
        url: /app3/v3/api-docs
        # 服务名称(Optional)
        service-name: baian-cloud-test-app3
        # 路由前缀
        context-path: /app3
        # 排序
        order: 3

全局添加自定义头

java 复制代码
package com.baian.common.core.config;


import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.HeaderParameter;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;

import java.util.List;

/**
 * @program: baian-cloud
 * @description: 为每个接口添加鉴权
 * @author: <航迹者-694204477@qq.com>
 * @create: 2024-07-02 10:21
 **/
@Slf4j
@Configuration
public class Knife4jOperationCustomizer {

    @Value("${sa-token.token-name:Authorization}")
    private String securityHeaderName;

    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            // 全局添加鉴权参数
            if (openApi.getPaths() != null) {
                HeaderParameter parametersItem = new HeaderParameter();
                parametersItem.setName(securityHeaderName);
                parametersItem.setRequired(false);
                Schema<String> schema = new Schema<>();
                schema.setType("string");
                parametersItem.setSchema(schema);
                openApi.getPaths().forEach((s, pathItem) -> {
                    pathItem.readOperations().forEach(operation -> {
                        // 为所有接口添加请求头
                        operation.addParametersItem(parametersItem);
                        // 为所有接口添加鉴权
//                        operation.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
                    });
                });
            }
        };
    }
}

// https://doc.xiaominfo.com/docs/blog/add-authorization-header

注解: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")

实用新增注解:

@ParameterObject 

案例

@Tag(name = "用户接口")
@RestController
@RequestMapping("sys/user")
public class SysUserController {

    @Resource
    private ISysUserService sysUserService;

    @Operation(summary = "分页查询")
    @GetMapping("page")
    public AjaxResult queryPage(@ParameterObject SysUserPageDTO dto) {
        PageInfo page = sysUserService.queryPage(dto);
        return AjaxResult.success(page);
    }

    @Operation(summary = "详情")
    @GetMapping("{id}")
    public AjaxResult queryInfo(@PathVariable Long id) {
        SysUserDTO dto = sysUserService.queryById(id);
        return AjaxResult.success(dto);
    }

    @Operation(summary = "新增")
    @PostMapping
    public AjaxResult save(@RequestBody SysUserDTO dto) {
        Long id = sysUserService.saveInfo(dto);
        return AjaxResult.success(id);
    }
}

@Getter
@Setter
@TableName("user")
@Schema(name = "User", description = "$!{table.comment}")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Schema(description = "主键")
    @TableId("id")
    private Long id;

    @Schema(description = "用户名")
    @TableField("name")
    private String name;

    @Schema(description = "手机号")
    @TableField("phone")
    private String phone;

    @Schema(description = "性别")
    @TableField("sex")
    private String sex;

    @Schema(description = "状态 0:禁用,1:正常")
    @TableField("status")
    private Integer status;
}

其他参考:

https://gitee.com/-/ide/project/xiaoym/swagger-bootstrap-ui-demo/edit/master/-/knife4j-spring-boot3-demo/src/main/java/com/github/xiaoymin/boot3/config/SwaggerConfig.java

https://blog.csdn.net/m0_74055560/article/details/134348304

福利配置: 自动转发。

java 复制代码
package com.baian.common.core.config;

import io.undertow.servlet.spec.HttpServletRequestImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @program: baian-cloud
 * @description: resource
 * @author: <航迹者-694204477@qq.com>
 * @create: 2024-07-02 08:51
 **/
@RestController
@Slf4j
public class BaiAnResourceCtl {

    @GetMapping("/")
    public void context(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.error("=====baian-cloud-common-web-core=======com.baian.common.core.config.BaiAnResourceCtl=================默认根path/====重定向到/doc.html==========");
        if (request instanceof HttpServletRequestImpl undertow) {
            String resolvedPath = undertow.getExchange().getResolvedPath();
            response.sendRedirect(resolvedPath + "/doc.html");
            return;
        }
        response.sendRedirect("/doc.html");
    }

}
相关推荐
2301_8112743112 分钟前
大数据基于Spring Boot的化妆品推荐系统的设计与实现
大数据·spring boot·后端
编程重生之路1 小时前
Springboot启动异常 错误: 找不到或无法加载主类 xxx.Application异常
java·spring boot·后端
politeboy1 小时前
k8s启动springboot容器的时候,显示找不到application.yml文件
java·spring boot·kubernetes
世间万物皆对象8 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
qq_17448285759 小时前
springboot基于微信小程序的旧衣回收系统的设计与实现
spring boot·后端·微信小程序
代码小鑫11 小时前
A043-基于Spring Boot的秒杀系统设计与实现
java·开发语言·数据库·spring boot·后端·spring·毕业设计
真心喜欢你吖11 小时前
SpringBoot与MongoDB深度整合及应用案例
java·spring boot·后端·mongodb·spring
周全全12 小时前
Spring Boot + Vue 基于 RSA 的用户身份认证加密机制实现
java·vue.js·spring boot·安全·php
飞升不如收破烂~13 小时前
Spring boot常用注解和作用
java·spring boot·后端
计算机毕设源码qq-383653104113 小时前
(附项目源码)Java开发语言,215 springboot 大学生爱心互助代购网站,计算机毕设程序开发+文案(LW+PPT)
java·开发语言·spring boot·mysql·课程设计