SpringBoot(九):整合Knife4j

郎家岭伯爵 2023年07月18日 265次浏览

前言

SpringBoot 整合 Knife4j。十分方便的接口文档工具,非常推荐后端开发尝试使用。

Knife4j 是美化、强化后的 SwaggerKnife4j 更加小巧、轻量,并且功能更加强大。

实现

创建一个 SpringBoot 项目。

pom.xml

pom.xml 文件中引入如下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>

application.properties

application.properties 中添加如下配置项:

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

controller层接口

在 controller 层添加如下接口:

package com.langjialing.knife4jdemo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @author 郎家岭伯爵
 * @time 2023/7/18 14:07
 */
@Api(tags = "测试 Knife4j")
@RestController
@RequestMapping("/knife4j")
public class Knife4jController {

    @ApiOperation("测试")
    @RequestMapping(value ="/test", method = RequestMethod.POST)
    public String test() {
        return "郎家岭伯爵";
    }

    @ApiOperation("测试2")
    @GetMapping("/test2")
    public String test2(@RequestParam String name){
        return "Hello," + name;
    }
}

访问Knife4j文档

启动项目后,在浏览器中输入如下地址可访问 Knife4j 文档:

http://localhost:8080/doc.html

注意:这里 http://localhost:8080/swagger-ui/ Swagger 文档也是可以访问的。

Knife4j文档

调用接口

调用需传参的接口

Knife4j 还有很多其它好用的功能,详情可查看官方文档

总结

SpringBoot 整合 Knife4j

赞助页面示例