SpringBoot整合Knife4j

什么是Knife4j

在日常开发中,写接口文档是我们必不可少的,而Knife4j就是一个接口文档工具,可以看作是Swagger的升级版,但是界面比Swagger更好看,功能更丰富。

整合

pom依赖

xml 复制代码
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>

yml配置文件

yaml 复制代码
spring:
  application:
    name: springboot-demo
  mvc:
    pathmatch:
      # Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
      # 所以需要配置此参数
      matching-strategy: ant_path_matcher

创建swagger配置类

kotlin 复制代码
package com.example.springbootdemo.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * <p>
 *  Swagger配置类
 * </p>
 *
 * @author yurenwei
 * @since 2023/9/20
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket webApiConfig() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 创建接口文档的具体信息
                .apiInfo(webApiInfo())
                // 创建选择器,控制哪些接口被加入文档
                .select()
                // 指定@ApiOperation标注的接口被加入文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo webApiInfo() {
        return new ApiInfoBuilder()
                // 文档标题
                .title("用户管理系统接口文档")
                // 文档描述
                .description("描述:本文档描述了用户管理系统统的接口定义")
                // 版本
                .version("1.0")
                // 联系人信息
                .contact(new Contact("yurenwei", "", ""))
                // 版权
                .license("")
                // 版权地址
                .licenseUrl("")
                .build();
    }

}

实体类增加swagger注解

kotlin 复制代码
package com.example.springbootdemo.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.example.springbootdemo.enums.GenderEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>
 *  用户实体类
 * </p>
 *
 * @author yurenwei
 * @since 2023/9/7
 */
@ApiModel(value = "用户参数", description = "用户参数")
@Data
@Accessors(chain = true)
@TableName("user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键id
     */
    @ApiModelProperty(value = "主键id")
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private Long id;

    /**
     * 姓名
     */
    @ApiModelProperty(value = "姓名")
    private String userName;

    /**
     * 手机号
     */
    @ApiModelProperty(value = "手机号")
    private String phone;

    /**
     * 性别
     */
    @ApiModelProperty(value = "性别")
    private GenderEnum gender;

    /**
     * 地址
     */
    @ApiModelProperty(value = "地址")
    private String address;

    /**
     * 状态(0、禁用1、启用)
     */
    @ApiModelProperty(value = "状态(0、禁用1、启用)")
    private Boolean status;

    /**
     * 注册时间
     */
    @ApiModelProperty(value = "注册时间")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime registerTime;

    /**
     * 创建人
     */
    @ApiModelProperty(value = "创建人")
    private Long createBy;

    /**
     * 创建时间
     */
    @ApiModelProperty(value = "创建时间")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 修改人
     */
    @ApiModelProperty(value = "修改人")
    private Long updateBy;

    /**
     * 修改时间
     */
    @ApiModelProperty(value = "修改时间")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    /**
     * 是否删除(0、否1、是)
     */
    @ApiModelProperty(value = "是否删除(0、否1、是)")
    private Boolean isDeleted;
}

controller增加swagger注解

less 复制代码
package com.example.springbootdemo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.mybatisplus.IUserService;
import com.example.springbootdemo.sevice.UserService;
import com.example.springbootdemo.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  用户控制器
 * </p>
 *
 * @author yurenwei
 * @since 2023/9/7
 */

@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserService userService;

    @ApiOperation("新增")
    @PostMapping("/add")
    public Result add(@RequestBody User params){
        userService.add(params);
        return Result.ok();
    }

    @ApiOperation("修改")
    @PostMapping("/update")
    public Result update(@RequestBody User params){
        userService.update(params);
        return Result.ok();
    }

    @ApiOperation("详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "Long")
    })
    @GetMapping("/queryDetail/{id}")
    public Result<User> update(@PathVariable Long id){
        return Result.ok(userService.queryDetails(id));
    }

    @ApiOperation("删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "Long")
    })
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        userService.delete(id);
        return Result.ok();
    }

    @ApiOperation("查询所有")
    @GetMapping("/getAll")
    public Result<List<User>> getAll(){
        return Result.ok(userService.getAll());
    }

    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "size", value = "每页记录数", required = true, dataType = "Long")
    })
    @GetMapping("/page")
    public Result<Page<User>> page(@RequestParam Long current,@RequestParam Long size){
        Page<User> pageParams = new Page<>(current, size);
        return Result.ok(iUserService.page(pageParams));
    }

    @ApiOperation("导入")
    @PostMapping("/importUser")
    public Result importUser(@RequestParam(value = "file") MultipartFile file){
        userService.importUser(file);
        return Result.ok();
    }

    @ApiOperation("导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        userService.export(response);
    }
}

测试

启动项目后访问http://127.0.0.1:8080/doc.html 出现如下界面说明整合成功

在Knife4j上进行调试接口

成功返回数据库里面数据

至此,SpringBoot整合Knife4j结束了。

相关推荐
weixin_438335401 分钟前
springboot 中添加TCP连接服务端
spring boot·后端·tcp/ip
程序猿毕设源码分享网18 分钟前
基于springboot校园招聘系统源码和论文
java·spring boot·后端
山山而川粤33 分钟前
美食推荐系统|Java|SSM|JSP|
java·开发语言·后端·学习·mysql
小小药35 分钟前
012-spring的注解开发
java·后端·spring
AI人H哥会Java1 小时前
【Spring】基于XML的Spring容器配置——Bean的作用域
java·开发语言·后端·spring·架构
vvw&2 小时前
如何在 Ubuntu 22.04 上安装 Elasticsearch
linux·运维·服务器·后端·ubuntu·elasticsearch·搜索引擎
uhakadotcom2 小时前
2025年java技术发展趋势展望
java·后端·架构
uhakadotcom2 小时前
2025年大语言模型RAG技术趋势展望
后端·算法·架构
xiaocaibao7772 小时前
Rust语言的数据库编程
开发语言·后端·golang
LeonNo112 小时前
golang,多个proxy拉包的处理逻辑
开发语言·后端·golang