Skip to content

引言

Knife4jSwagger 的增强版,专为 Java 开发者设计。它提供了以下核心功能:

  • 增强的 UI 界面:更美观、更易用的文档界面。
  • 离线文档导出:支持导出 Markdown、HTML、Word 等格式的文档。
  • 接口搜索:快速查找 API 接口。
  • 文件上传支持:增强文件上传功能。
  • 权限控制:支持文档权限控制,保护敏感 API

添加依赖

项目中使用 Knife4j 生成在线 API 文档,在 pom.xml 中添加 Knife4j 的依赖:

js
<!-- 依赖声明 -->
<dependencies>
    <!-- knife4j+OpenAI3+SpringDoc+接口文档  -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

Knife4j 是基于 Swagger 的增强工具,因此会自动引入 Swagger 的相关依赖。

配置文件

Knife4 对应的 YML 配置文件 application-knife4j.yml 内容如下:

js
# knife4j的增强配置
knife4j:
  # 开启knife4j,无需添加@EnableKnife4j注解
  enable: true
  # 生产环境建议设置为 true,禁用文档
  production: false
#  # 确保以下路径加上了API前缀
#  doc-api:
#    api-prefix: /api/
  openapi:
    title: 小蚂蚁云在线API文档
    description: 小蚂蚁接口文档说明
    email: xiaomayicloud@163.com
    version: v1.0
    # 文档定义配置
    scheme: Bearer
    # 文档访问头
    header: Authorization
    # 联系人
    contact: 小蚂蚁
    # 网址
    url: https://www.xiaomayicloud.com
    license: Apache 2.0
    license-url: https://www.xiaomayicloud.com
    terms-of-service-url: https://www.xiaomayicloud.com
  # 是否启用登录认证
  basic:
    # 开启SwaggerBasic认证功能,默认是false
    enable: false
    # Basic认证用户名
    username: admin
    # Basic认证密码
    password: 123456
  # 前端UI的个性化配置属性
  setting:
    # 显示语言中文
    language: zh_cn
    # 开启版本
    enable-version: true
    # 是否显示界面中SwaggerModel功能
    enable-swagger-models: true
    # 重命名SwaggerModel名称,默认
    swagger-model-name: SwaggerModel2
    # 是否显示界面中"文档管理"功能
    enable-document-manage: true
  documents:
    - name: 文档说明
      locations: classpath:markdown/*
      group: default

温馨提示

上述配置文件项目中已包含,此处主要用于描述集成使用案例,便于企业和开发者能更好的理解。

文档配置

项目中在线文档是专门的模块 xiaomayi-springdoc ,配置类,通过配置类 Knife4jConfig 定义 OpenAPI 的基本信息(如标题、描述、版本等)。

js
package com.xiaomayi.springdoc.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
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 io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * <p>
 * 在线文档配置类
 * </p>
 *
 * @author 小蚂蚁云团队
 * @since 2024-05-21
 */
@Configuration
public class Knife4jConfig {

    /**
     * SpringDoc 标题、描述、版本等信息配置
     *
     * @return openApi 配置信息
     */
    @Bean
    public OpenAPI springDocOpenAPI() {
        return new OpenAPI()
                // 设置文档API前缀
                .info(new Info()
                        // 接口文档标题
                        .title(Knife4jProperties.getTitle())
                        // 接口文档简介
                        .description(Knife4jProperties.getDescription())
                        // 接口文档版本
                        .version(Knife4jProperties.getVersion())
                        .license(new License()
                                .name(Knife4jProperties.getTitle())
                                .url(Knife4jProperties.getUrl()))
                        // 开发者联系方式
                        .contact(new Contact()
                                .name(Knife4jProperties.getContact())
                                .email(Knife4jProperties.getEmail())))
                // 设置服务器URL前缀
                .servers(List.of(new Server().url("/api")))
                .externalDocs(new ExternalDocumentation()
                        .description(Knife4jProperties.getDescription())
                        .url(Knife4jProperties.getUrl()));
    }
}

注解使用

在控制器和方法上使用 OpenAPI 注解(如 @Tag@Operation 等)来描述 API,实例如下:

js
package com.xiaomayi.admin.controller;

import cn.hutool.http.HttpStatus;
import com.xiaomayi.core.config.AppConfig;
import com.xiaomayi.core.exception.BizException;
import com.xiaomayi.core.utils.R;
import com.xiaomayi.excel.utils.ExcelUtil;
import com.xiaomayi.logger.annotation.RequestLog;
import com.xiaomayi.logger.enums.RequestType;
import com.xiaomayi.system.dto.level.LevelAddDTO;
import com.xiaomayi.system.dto.level.LevelListDTO;
import com.xiaomayi.system.dto.level.LevelPageDTO;
import com.xiaomayi.system.dto.level.LevelUpdateDTO;
import com.xiaomayi.system.service.LevelService;
import com.xiaomayi.system.vo.level.LevelExcelVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 职级 前端控制器
 * </p>
 *
 * @author 小蚂蚁云团队
 * @since 2024-03-23
 */
@RestController
@RequestMapping("/level")
@Tag(name = "职级管理", description = "职级管理")
@AllArgsConstructor
public class LevelController {

    private final LevelService levelService;

    /**
     * 查询分页列表
     *
     * @param levelPageDTO 查询条件
     * @return 返回结果
     */
    @Operation(summary = "查询分页列表", description = "查询分页列表")
    @PreAuthorize("@pms.hasAuthority('sys:level:page')")
    @GetMapping("/page")
    public R page(LevelPageDTO levelPageDTO) {
        return R.ok(levelService.page(levelPageDTO));
    }

    /**
     * 查询数据列表
     *
     * @param levelListDTO 查询条件
     * @return 返回结果
     */
    @Operation(summary = "查询数据列表", description = "查询数据列表")
    @PreAuthorize("@pms.hasAuthority('sys:level:list')")
    @GetMapping("/list")
    public R getList(LevelListDTO levelListDTO) {
        return R.ok(levelService.getList(levelListDTO));
    }

    /**
     * 根据ID查询详情
     *
     * @param id 职级ID
     * @return 返回结果
     */
    @Operation(summary = "根据ID查询详情", description = "根据ID查询详情")
    @PreAuthorize("@pms.hasAuthority('sys:level:detail')")
    @GetMapping("/detail/{id}")
    public R getDetail(@PathVariable("id") Integer id) {
        return R.ok(levelService.getDetail(id));
    }

    /**
     * 添加职级
     *
     * @param levelAddDTO 参数
     * @return 返回结果
     */
    @Operation(summary = "添加职级", description = "添加职级")
    @RequestLog(title = "添加职级", type = RequestType.INSERT)
    @PreAuthorize("@pms.hasAuthority('sys:level:add')")
    @PostMapping("/add")
    public R add(@RequestBody @Validated LevelAddDTO levelAddDTO) {
        return levelService.add(levelAddDTO);
    }

    /**
     * 更新职级
     *
     * @param levelUpdateDTO 参数
     * @return 返回结果
     */
    @Operation(summary = "更新职级", description = "更新职级")
    @RequestLog(title = "更新职级", type = RequestType.UPDATE)
    @PreAuthorize("@pms.hasAuthority('sys:level:update')")
    @PutMapping("/update")
    public R update(@RequestBody @Validated LevelUpdateDTO levelUpdateDTO) {
        return levelService.update(levelUpdateDTO);
    }

    /**
     * 删除职级
     *
     * @param id 记录ID
     * @return 返回结果
     */
    @Operation(summary = "删除职级", description = "删除职级")
    @RequestLog(title = "删除职级", type = RequestType.DELETE)
    @PreAuthorize("@pms.hasAuthority('sys:level:delete')")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        return levelService.delete(id);
    }

    /**
     * 批量删除职级
     *
     * @param idList 记录ID
     * @return 返回结果
     */
    @Operation(summary = "批量删除职级", description = "批量删除职级")
    @RequestLog(title = "批量删除职级", type = RequestType.BATCH_DELETE)
    @PreAuthorize("@pms.hasAuthority('sys:level:batchDelete')")
    @DeleteMapping("/batchDelete")
    public R batchDelete(@RequestBody @Validated List<Integer> idList) {
        return levelService.batchDelete(idList);
    }

    /**
     * 导出职级
     *
     * @return 返回结果
     */
    @RequestLog(title = "导出职级", type = RequestType.EXPORT)
    @Operation(summary = "导出职级", description = "导出职级")
    @PreAuthorize("@pms.hasAuthority('sys:level:export')")
    @GetMapping("/export")
    public R exportLevel(LevelListDTO levelListDTO) {
        return levelService.exportLevel(levelListDTO);
    }

    /**
     * 导入职级
     *
     * @param file 文件
     * @return 返回结果
     * @throws Exception 异常处理
     */
    @RequestLog(title = "导入职级", type = RequestType.IMPORT)
    @Operation(summary = "导入职级", description = "导入职级")
    @PreAuthorize("@pms.hasAuthority('sys:level:import')")
    @PostMapping("/import")
    public R importLevel(MultipartFile file) throws Exception {
        // 实例化导出对象工具
        ExcelUtil<LevelExcelVO> util = new ExcelUtil<>(LevelExcelVO.class);
        // 获取导入数据源
        List<LevelExcelVO> list = util.importExcel(file.getInputStream());
        // 导入数据源
        return levelService.importLevel(list);
    }

}

访问文档

启动项目后,访问以下 URL 查看 Knife4j 文档:

js
Knife4j UIhttp://localhost:8081/api/doc.html
Swagger UIhttp://localhost:8081/api/swagger-ui/index.html
OpenAPI JSONhttp://localhost:8081/api/v3/api-docs

Knife4j

Knife4j

Knife4j

注意事项

  1. 生产环境禁用文档:在生产环境中,建议通过配置 knife4j.production=true 禁用文档,避免暴露。
  2. 接口分组:如果需要为不同模块的接口分组,可以在 Docket 配置中设置多个分组。
  3. Knife4j 版本:确保使用最新版本的 Knife4j,以获得更好的功能和兼容性。

总结

可以在项目中轻松集成 Knife4j,并生成功能强大、界面友好的 API 文档。Knife4j 不仅兼容 Swagger,还提供了更多实用功能(如离线文档导出、接口搜索、动态参数调试等),非常适合企业级项目的 API 文档管理。

小蚂蚁云团队 · 提供技术支持

小蚂蚁云 新品首发
新品首发,限时特惠,抢购从速! 全场95折
赋能开发者,助理企业发展,提供全方位数据中台解决方案。
获取官方授权