Spring|Spring Boot项目集成Knife4j接口文档的实例代码

目录

  • 1、在pom.xml引入依赖包
  • 2、创建Knife4j配置文件
  • 3、使用Knife4j注解
  • 4、全局参数
Knife4j就相当于是swagger的升级版,对于我来说,它比swagger要好用得多

1、在pom.xml引入依赖包
com.github.xiaoyminknife4j-spring-boot-starter2.0.9


2、创建Knife4j配置文件
package com.yuyun.config; import io.swagger.annotations.ApiOperation; import io.swagger.models.auth.In; 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.ApiKey; import springfox.documentation.service.Contact; import springfox.documentation.service.SecurityScheme; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @author hyh */@Configuration@EnableSwagger2WebMvcpublic class Knife4jConfiguration {@Bean(value = "https://www.it610.com/article/defaultApi2")public Docket defaultApi2() {Docket docket = new Docket(DocumentationType.SWAGGER_2)// 是否启用Swagger.enable(true)//分组名称.groupName("1.0版本")// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息).apiInfo(apiInfo())// 设置哪些接口暴露给Swagger展示.select()// 扫描所有有注解的api,用这种方式更灵活.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//指定Controller扫描包路径//.apis(RequestHandlerSelectors.basePackage("com.yuyun.controller"))// 扫描所有//.apis(RequestHandlerSelectors.any()).build(); return docket; }private ApiInfo apiInfo() {String name = "雨云"; String url = "https://www.xxx.com/"; String email = "1873591403@qq.com"; Contact contact = new Contact(name, url, email); return new ApiInfoBuilder().title("API接口文档").description("API接口文档描述").termsOfServiceUrl("https://www.xx.com/").contact(contact).version("1.0.1").build(); }}

注意:如果出现错误Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

是因为SpringBoot版本高了,将版本降下去或者在application.yml添加如下内容即可解决该错误
spring: mvc:pathmatch:matching-strategy: ant_path_matcher

项目运行后,访问ip+端口号+/doc.html,比如http://localhost:8110/doc.html。效果如图
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片


3、使用Knife4j注解 (1)在实体类中使用
@ApiModel 放在在响应实体类上,用于描述该类
@ApiModelProperty 描述该响应类的属性
/** * 企业信息表 * * @author * @since 1.0.0 2021-12-17 */@Data@ApiModel(value = "https://www.it610.com/article/企业信息表")@TableName("company")public class CompanyDTO implements Serializable {private static final long serialVersionUID = 1L; /*** 主键*/ @ApiModelProperty(value = "https://www.it610.com/article/主键") private Long id; /*** 企业名称*/ @ApiModelProperty(value = "https://www.it610.com/article/企业名称") private String companyName; /*** 简介*/ @ApiModelProperty(value = "https://www.it610.com/article/简介") private String description; }

Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

(2)在Controller层使用
@RestController@RequestMapping("company")@Api(tags = "企业信息表")public class CompanyController {@Autowiredprivate CompanyService companyService; @GetMapping("getList")@ApiOperation("根据条件获取数据")@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "https://www.it610.com/article/id", paramType = "query", required = true, dataType = "String"),@ApiImplicitParam(name = "name", value = "https://www.it610.com/article/名称", paramType = "query", required = true, dataType = "String")})public Result> getList(@ApiParam(name = "address", value = "https://www.it610.com/article/地址", required = true)String address) {List companyList = companyService.list(); return new Result>().success(companyList); }}

还有其他一些注解,用到再了解

4、全局参数 在实际项目中访问接口都添加了权限,每次访问都要带一个请求头参数token。全局参数就是为了方便传一个固定的参数。当添加全局参数后,所有的接口都会带上该参数。
第一种
在配置文件中加入
private List securitySchemes() {List apiKeyList = new ArrayList(); apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue())); return apiKeyList; }

defaultApi2()方法内引用
.securitySchemes(securitySchemes())

最后配置文件中的内容:
@Configuration@EnableSwagger2WebMvcpublic class Knife4jConfiguration {@Bean(value = "https://www.it610.com/article/defaultApi2")public Docket defaultApi2() {Docket docket = new Docket(DocumentationType.SWAGGER_2)// 是否启用Swagger.enable(true)//分组名称.groupName("1.0版本")// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息).apiInfo(apiInfo())// 设置哪些接口暴露给Swagger展示.select()// 扫描所有有注解的api,用这种方式更灵活.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//指定Controller扫描包路径//.apis(RequestHandlerSelectors.basePackage("com.yuyun.controller"))// 扫描所有//.apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()/* 设置安全模式,swagger可以设置访问token */.securitySchemes(securitySchemes()).securityContexts(securityContexts()).pathMapping("/"); return docket; }private ApiInfo apiInfo() {String name = "雨云"; String url = "https://www.xxx.com/"; String email = "1873591403@qq.com"; Contact contact = new Contact(name, url, email); return new ApiInfoBuilder().title("API接口文档").description("API接口文档描述").termsOfServiceUrl("https://www.xx.com/").contact(contact).version("1.0.1").build(); }/*** 安全模式,这里指定token通过Authorization头请求头传递*/private List securitySchemes() {List apiKeyList = new ArrayList(); apiKeyList.add(new ApiKey("Authorization", "Authorization", "header")); return apiKeyList; }/*** 安全上下文*/private List securityContexts() {List securityContexts = new ArrayList<>(); securityContexts.add(SecurityContext.builder().securityReferences(defaultAuth()).build()); return securityContexts; }/*** 默认的安全上引用*/private List defaultAuth() {AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; List securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("Authorization", authorizationScopes)); return securityReferences; }}

效果:菜单上多了一个Authorize,在参数值中添加上信息
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

刷新一下,再打开接口就会发现多了个请求头部
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

第二种
直接在菜单文档管理全局参数设置,然后添加参数:
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片

再打开接口就会发现请求头参数加上了
Spring|Spring Boot项目集成Knife4j接口文档的实例代码
文章图片


源码地址:https://gitee.com/hyh17808770899/spring-boot/tree/master/springboot-03
【Spring|Spring Boot项目集成Knife4j接口文档的实例代码】到此这篇关于Spring Boot项目集成Knife4j接口文档的文章就介绍到这了,更多相关Spring Boot集成Knife4j接口文档内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读