学而实习之 不亦乐乎

springboot 整合 knife4j 实现在线接口文档

2023-03-26 21:05:59

一、引入 knife4j

knife4j 主要的版本基本如下所示

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

注意:knife4j 已经引入了 springfox,所以在使用的时候无需再次引入springfox,否则有可能会导致版本冲突,如果你在网关聚合时,必须禁用 knife4j 的增强功能。使用Knife4j2.0.6及以上的版本,Spring Boot的版本必须大于等于2.2.x。

二、创建 Swagger 配置依赖

package com.demo.test.config.kinfe4j;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Knife4jConfiguration {
    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        String groupName="3.X版本";
        Docket docket=new Docket(DocumentationType.OAS_30)
                .apiInfo(new ApiInfoBuilder()
                        .title("这是knife4j API ")
                        .description("# 这里记录服务端所有的接口的入参,出参等等信息")
                        .termsOfServiceUrl("http://yaomaoyang.com")
                        .contact(new Contact("逆流星","http://yaomaoyang.com","361426201@qq.com"))
                        .version("3.0")
                        .build())
                //分组名称
                .groupName(groupName)
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.ymy.notes.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}

这里需要注意一点,如果你使用的是 2.x,那么需要将 @EnableSwagger2 替换成 @EnableSwagger2WebMvc, 因为 @EnableSwagger2 是在 3.x 才引入的注解,并且将@EnableSwagger2WebMvc 设置为不推荐使用。

三、配置项目名和端口信息

server:
  port: 8818
spring:
  application:
    name: notes

四、创建一个简单的 RESTful 接口

package com.demo.test.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/test")
@Api(tags = "测试swagger")
public class Knife4jTestController {
    @GetMapping(value = "/hello")
    @ApiImplicitParam(name = "name",value = "姓名",required = true)
    @ApiOperation("测试接口")
    public String test(@RequestParam("name") String name){
        return "hello "+name+", I am  meimei han";
    }
}

启动项目
如果你在启动项目的时候抛出:Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException

极有可能是版本太高,应该是 2.6.x,由于 Springfox 使用的路径匹配是基于 AntPathMatcher,而Spring Boot 2.6.X 使用的是 PathPatternMatcher,所以将MVC的路径匹配规则改成 AntPathMatcher,在配置文件中加入如下参数即可。

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

启动成功之后,在浏览器中访问:http://127.0.0.1:8818/doc.html。到此为止,knife4j 已经完美的运行起来了。

五、knife4j 的增强功能

以上只是 knife4j 的基础用法,knife4j 还有很多强大的功能,如:i18n国际化、接口添加作者、自定义文档、访问权限控制、接口排序、到处离线文档、过滤请求参数等等,这些都是 knife4j 的增强功能,那如何开启 knife4j 的增强功能呢?

Knife4j 自 2.0.6 版本开始,将目前在Ui界面中一些个性化配置剥离,开发者可以在后端进行配置,并且提供的 knife4j-spring-boot-strater 组件自动装载,开发者可以在配置文件中决定需要开启的功能。

1、knife4j 中的参数

springboot 中 knife4j的完整参数如下:

knife4j:
  # 是否开启增强功能
  enable: true
  # 自定义文档集合
  documents:
      group: 2.X版本
      name: 接口签名
      locations: classpath:sign/*
  # UI的个性化设置
  setting:
    language: zh-CN
    enableSwaggerModels: true
    enableDocumentManage: true
    swaggerModelName: 实体类列表
    enableVersion: false
    enableReloadCacheParameter: false
    enableAfterScript: true必须开启。包括后面所讲解到的所有增强功能,都需要设置这个参数。# 具体接口的过滤类型
    enableFilterMultipartApiMethodType: POST
    # 针对 RequestMapping 的接口请求类型,默认会显示7个,开启后只显示 POST 类型接口地址。
    enableFilterMultipartApis: false
    enableRequestCache: true
    enableHost: false
    enableHostText: 192.168.0.193:8000
    # 自定义主页
    enableHomeCustom: true
    homeCustomLocation: classpath:markdown/home.md
    enableSearch: false
    enableFooter: false
    enableFooterCustom: true
    footerCustomContent: Apache License 2.0 | Copyright  2019
    enableDynamicParameter: false
    enableDebug: true
    enableOpenApi: false
    enableGroup: true
  #是否开启一个默认的跨域配置, 
  cors: false
  #是否开启生产环境保护策略
  production: false
  #提供 BasicHttp 校验,保护文档
  basic:
    enable: false
    username: test
    password: 12313

knife4j 的增强功能是需要开启的,默认关闭,开启也是十分的简单,在以前的版本中,开发者需要在配置文件中手动使用 @EnableKnife4j 来使用增强,自 2.0.6 版本后,只需要在配置文件中配置 knife4j.enable=true 即可,不在使用注解。

注意:要使用Knife4j提供的增强,knife4j.enable=true必须开启。包括后面所讲解到的所有增强功能,都需要设置这个参数。

2、接口添加作者

使用方式:添加注解 @ApiOperationSupport(author = "Tester007")

@GetMapping(value = "/hello")
@ApiImplicitParam(name = "name",value = "姓名",required = true)
@ApiOperation("测试接口")
@ApiOperationSupport(author = "Tester007")
public String test(@RequestParam("name") String name){
    return "hello "+name+", I am  meimei han";
}

在每个接口上都加上这个注解,着实有点浪费时间了,所以 knife4j 在收到反馈之后,决定在 Controller 类上增加一个注解,表示当前接口类下的所有接口都是该作者负责开发。因此在 2.0.3 版本中新增加了 @ApiSupport 注解,该注解目前有两个属性,分别是 author(作者) 和 order(排序)

注意:如果在controller 类上添加了@ApiSuppor 注解,并且在某个接口上也添加了 @ApiOperationSupport 注解,那么接口上的作者将会覆盖 controller 类上的作者

@RestController
@RequestMapping(value = "/test")
@ApiSupport(author = "Tester007-controller")
@Api(tags = "测试swagger")
public class Knife4jTestController {
    @GetMapping(value = "/hello")
    @ApiImplicitParam(name = "name",value = "姓名",required = true)
    @ApiOperation("测试接口")
    @ApiOperationSupport(author = "逆流星逆流星007-test")
    public String hello(@RequestParam("name") String name){
        return "hello "+name+", I am  meimei han";
    }
}