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: <航迹者[email protected]>
 * @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: <航迹者[email protected]>
 * @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");
    }

}
相关推荐
跟着珅聪学java2 小时前
spring boot +Elment UI 上传文件教程
java·spring boot·后端·ui·elementui·vue
我命由我123452 小时前
Spring Boot 自定义日志打印(日志级别、logback-spring.xml 文件、自定义日志打印解读)
java·开发语言·jvm·spring boot·spring·java-ee·logback
战族狼魂5 小时前
CSGO 皮肤交易平台后端 (Spring Boot) 代码结构与示例
java·spring boot·后端
用键盘当武器的秋刀鱼9 小时前
springBoot统一响应类型3.5.1版本
java·spring boot·后端
小李同学_LHY9 小时前
三.微服务架构中的精妙设计:服务注册/服务发现-Eureka
java·spring boot·spring·springcloud
爱喝醋的雷达11 小时前
Spring SpringBoot 细节总结
java·spring boot·spring
嘵奇13 小时前
深入解析 Spring Boot 测试核心注解
java·spring boot·后端
技术liul14 小时前
解决Spring Boot Configuration Annotation Processor not configured
java·spring boot·后端
腥臭腐朽的日子熠熠生辉17 小时前
解决maven失效问题(现象:maven中只有jdk的工具包,没有springboot的包)
java·spring boot·maven
绝顶少年19 小时前
Spring Boot 注解:深度解析与应用场景
java·spring boot·后端