一、Swagger介绍
项目进入前后端分离开发模式后,api文档是最好的沟通方式。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,拥有着以下优点:
-
及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
-
规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
-
一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
-
可测性 (直接在接口文档上进行测试,以方便理解业务)
二、集成knife4j
💡这里就会问了,不是集成Swagger吗,怎么是
knife4j
?
回答一下:knife4j可以理解为是基于Swagger的增强版UI框架
,提供了更加完善的交互体验和更加美观的UI设计,同时,它也提供了更多的扩展功能,例如在线调试和多语言支持等。
1、添加依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.8</version>
</dependency>
2、添加knife4j配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
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:letian
* @description: Knife4j配置类
* @version: 1.0
*/
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
@Bean
public Docket adminApiConfig(){
List<Parameter> pars = new ArrayList<>();
ParameterBuilder tokenPar = new ParameterBuilder();
tokenPar.name("token")
.description("用户token")
.defaultValue("")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
pars.add(tokenPar.build());
//添加head参数end
Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
.groupName("adminApi")
.apiInfo(adminApiInfo())
.select()
//这里指定扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.letian"))
//只显示admin路径下的页面
// .paths(PathSelectors.regex("/admin/.*"))
.build()
.globalOperationParameters(pars);
return adminApi;
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title("后台管理系统-API文档")
.description("本文档描述了后台管理系统微服务接口定义")
.version("1.0")
.contact(new Contact("letian", "http://letian.com", "letian@qq.com"))
.build();
}
}
3、浏览器启动测试:localhost:8080(你自己的端口号).doc.html
💡如果显示上方页面就表示成功了~
三、踩到的坑
❗如果你按照上面步骤顺利打开了 Knife4j 的文档管理页面,那第三节的内容可以略过直接去看第四节。但如果你按照上边步骤搭建过程中控制台出现了下面报错信息,那不妨看看该怎么解决:
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
如果控制台报了这样的错误信息,那么你可以通过修改配置文件
来解决
💡在你的application.yml配置文件中加入以下信息即可解决:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
四、相关操作
- 测试接口
- 生成项目接口文档
如果本篇文章对你有帮助的话,请点个赞叭~