更轻量级的的Knf4j接口文档配置实战
什么是Knife4j?
Knife4j是一个为Java MVC框架集成Swagger生成API文档的增强解决方案,其前身是swagger-bootstrap-ui
。相比于原生的Swagger,Knife4j不仅提供了更加符合现代开发者使用习惯和审美的Web页面,还通过补充一些注解扩展了Swagger的功能。Knife4j以其小巧、轻量且功能强大的特点,成为了接口文档管理的优选工具。
核心功能
文档说明:
-
Knife4j能够详细列出接口文档的说明,包括接口地址、请求类型、请求示例、请求参数、响应示例、响应参数、响应码等信息。这些信息帮助开发者快速理解和使用API。
在线调试:
-
提供在线接口联调功能,自动解析当前接口参数,返回接口响应内容、headers、响应时间、响应状态码等信息。这一功能极大地方便了开发者在开发过程中进行接口调试。
接口搜索:
提供强大的接口搜索功能,支持按接口地址、请求方法、接口描述等关键字进行搜索。这使得在大型项目中快速定位特定接口变得轻而易举。
接口过滤:
-
提供接口过滤功能,可以根据接口分组、接口标签、接口地址等条件进行过滤。这一功能在管理大量接口时尤为有用。
自定义主题:
-
支持自定义主题,开发者可以根据项目需求定制个性化的API文档界面,提升用户体验。
丰富的扩展功能:
-
如接口排序、接口分组、接口标签等,进一步丰富了API文档管理的功能,使得文档更加结构化和易于管理。
依赖配置
在Spring Boot项目中,可以通过Maven引入Knife4j的依赖:
<!-- knife4j 依赖,接口文档工具 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
配置类
通过配置类Knife4jConfig
,可以自定义OpenAPI的信息,包括API的标题、版本、描述、服务条款、许可证以及作者信息等。
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class Knife4jConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("网盘系统 API")
.version("1.0")
.description("网盘系统")
.termsOfService("http://192.168.19.120")
.license(new License().name("Apache 2.0")
.url("https://www.baidu.com"))
// 添加作者信息
.contact(new Contact()
.name("hoo") // 替换为作者的名字
.email("") // 替换为作者的电子邮件
.url("") // 替换为作者的网站或个人资料链接
)
) ;
}
}
接口示例
以下是一个使用Knife4j注解的接口示例,展示了如何通过Knife4j生成详细的API文档。
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/file/v1")
@Tag(name = "文件管理接口", description = "提供文件和文件夹的管理功能")
public class AccountFileController {
@Autowired
private AccountFileService accountFileService;
@GetMapping("list")
@Operation(summary = "查询文件列表", description = "根据父文件夹ID查询文件列表")
public JsonData list(
@Parameter(description = "父文件夹ID", required = true, example = "1") @RequestParam(value = "parent_id") Long parentId) {
Long accountId = LoginInterceptor.threadLocal.get().getId();
List<AccountFileDTO> list = accountFileService.listFile(accountId, parentId);
return JsonData.buildSuccess(list);
}
}
访问地址
配置完成后,可以通过以下地址访问生成的API文档:
访问地址:http://{ip}:{port}/doc.html