7

Springboot中整合knife4j接口文档 - 北根娃

 2 years ago
source link: https://www.cnblogs.com/alanlin/p/16194566.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在项目开发过程中,web项目的前后端分离开发,APP开发,需要由前端后端工程师共同定义接口,编写接口文档,之后大家都根据这个接口文档进行开发。

什么是knife4j

简单说knife4j就swagger的升级版API文档的一个框架,但是用起来比swagger方便多了,UI更加丰富。

整合 knife4j

引入 maven 依赖

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <!--在引用时请在maven中央仓库搜索3.X最新版本号-->
    <version>3.0.3</version>
</dependency>

knife4j 配置文件

创建 Knife4jConfig 文件

package com.didiplus.common.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * Author: didiplus
 * Email: [email protected]
 * CreateTime: 2022/4/25
 * Desc: knife4j 配置
 */
@Configuration
@EnableKnife4j
public class Knife4jConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.didiplus"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot项目 后台服务API接口文档")
                .description("使用 knife4j 搭建的后台服务API接口文档")
                .termsOfServiceUrl("http://localhost:8080/")
                .contact("didiplus")
                .version("1.0.0")
                .build();
    }
}

配置API接口

package com.didiplus.modules.sys.controller;

import com.didiplus.modules.sys.domain.SysDictType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Author: didiplus
* Email: [email protected]
* CreateTime: 2022/4/25
* Desc: 数据字典控制器
*/
@RestController
@Api(tags = "数据字典")
@RequestMapping("/api/sys/dictType")
public class SysDictTypeController {
    
    @ApiOperation("添加")
    @PostMapping("/add")
    public SysDictType add() {
        SysDictType dictType = new SysDictType();
        dictType.setId("1");
        dictType.setTypeName("用户状态");
        dictType.setTypeCode("user_type");
        dictType.setDescription("用户状态");
        dictType.setEnable("true");
        return  dictType;
    }
    
}

通过 @Api注解标注需要生成接口文档,通过 @ApiOperation注解标注接口名。 同时我们给 SysDictType也加上对应的注解

package com.didiplus.modules.sys.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotEmpty;

/**
 * Author: didiplus
 * Email: [email protected]
 * CreateTime: 2022/4/25
 * Desc: 字典类型领域模型
 */

@Data
@ApiModel(value = "字典类型")
public class SysDictType {

    @ApiModelProperty("ID")
    private String id;

    @NotEmpty(message = "字典编码不能为空")
    @ApiModelProperty(name = "字典名称",example = "用户ID")
    private String typeName;

    @NotEmpty(message = "字典编码不能为空")
    @ApiModelProperty(value = "字典编码")
    private String typeCode;

    @ApiModelProperty(value = "字典描述")
    private String description;

    @NotEmpty(message = "字典状态不能为空")
    @ApiModelProperty(value = "字典状态")
    private String enable;
}

通过 @ApiModel标注这是一个参数实体,通过 @ApiModelProperty标注字段说明。
访问 http://localhost:8080/doc.html体验一下,出现访问资源异常

出现这个问题的原因是因为我们加上了 ResponseBodyAdvice统一处理返回值/响应体,导致给Swagger的返回值也包装了一层,UI页面无法解析。可以通过 http://localhost:8080/v2/api-docs?group=SwaggerDemo观察Swagger返回的json数据。

既然知道了问题原因那就很好解决了,我们只需要在ResponseBodyAdvice处理类中只转换我们自己项目的接口即可。

@RestControllerAdvice(basePackages = "com.didiplus.modules")
public class ResponseAdvice  implements ResponseBodyAdvice<Object> {
....省略....
}

详细的可以参考SpringBoot 如何统一后端返回格式。通过添加basePackage属性限定统一返回值的范围,这样就不影Swagger了 ,重启服务器再次访问swagger接口地址,就可以看到接口文档页面了。

knife4j 常用特性

knife4j 在 swagger 的基础上做了许多增强,这里介绍几个最常用的。使用增强特性需在application.yml 中开启 。

knife4j:
  production: false
  enable: true

前后端分离开发中一般使用 token 作为请求参数进行身份与权限鉴定,有放在 query(表单)和 header(请求头)的,knife4j 对这两种都进行了支持,只需在侧边栏‘文档管理 -> 全局参数设置’中设置。

有时我们需要一份离线文档可以随时随地进行查看,knife4j 支持导出四种格式( md、html、doc 、json)的离线文档,在侧边栏‘文档管理 -> 离线文档’中导出。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK