knife Gitee 地址:https://gitee.com/xiaoym/knife4j
接口生成利器 knife 介紹
之前項目中一直在使用 swagger 生成后台接口文檔,很好用,至少比之前用 word 寫接口文檔 postman 調試接口方便多了。swagger 提供了一套前端頁面,但是需要在代碼中加入注解,如: @Api
@ApiOperation
等,耦合度比較高,但使用起來很方便。對我強迫症的我來說,swagger-ui 頁面奇丑無比,給我的感覺就是特別亂,並且沒辦法保存常用的參數,使用起來很不方便。
這篇文章來介紹 knife,是 swagger 的增強版。該UI增強包主要包括兩大核心功能:文檔說明 和 在線調試
- 文檔說明:根據Swagger的規范說明,詳細列出接口文檔的說明,包括接口地址、類型、請求示例、請求參數、響應示例、響應參數、響應碼等信息,使用 knife 能根據該文檔說明,對該接口的使用情況一目了然。
- 在線調試:提供在線接口聯調的強大功能,自動解析當前接口參數,同時包含表單驗證,調用參數可返回接口響應內容、headers、Curl請求命令實例、響應時間、響應狀態碼等信息,幫助開發者在線調試,而不必通過其他測試工具測試接口是否正確,簡介、強大。並且可以實現緩存請求參數,設置header 或 query 全局參數和值。
功能不過多介紹,直接上圖演示:
springboot 整合 knife
springboot 基本框架搭建就不過多介紹了,直接演示 springboot 整合 knife 需要改動的配置。
pom.xml 文件增加依賴
由於是 springfox-swagger
的增強UI包,所以基礎功能依然依賴 swagger
,springfox-swagger
的 jar 包必須引入。然后引入 knife4j-spring-ui
替代原來的 swagger-ui
。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
<version>3.0.2</version>
</dependency>
編寫Swagger2Config配置文件
Swagger2Config 文件內容如下:
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("台接口")
.description("這里描述內容")
.contact(new Contact("Liuyanmin", "", ""))
.termsOfServiceUrl("http://localhost:60000/")
.version("1.0")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.host("http://localhost:60000/")
.groupName("后台接口")
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
訪問地址,knife
默認訪問地址是:http://${host}:${port}/doc.html
swagger-ui
的樣式頁面還是可以訪問的,地址:http://${host}:${port}/swagger-ui.html
,這個不建議使用了,頁面太丑了,了解一下就可以了。
注意事項
SpringBoot 中訪問 doc.html
或 swagger-ui.html
報404的解決辦法
@Configuration
public class IntercpetorConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 設置swagger靜態資源訪問
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Springfox-swagger
默認提供的接口和依賴的資源文件需要在攔截器或權限驗證中過濾掉,過濾內容如下:
/swagger-ui.html,/swagger-resources/**,/csrf,/webjars/**
總結
若項目中之前使用過 swagger
生成接口文檔,改成 knife
其實很簡單,只需要兩步:
- pom.xml 中把
swagger-ui
jar包替換成knife4j-spring-ui
- 訪問地址由原來的
http://${host}:${port}/swagger-ui.html
改成http://${host}:${port}/doc.html
就這么簡單。
還有更多優秀開源的接口文檔生成工具,感興趣的可以自己看一下。