演示环境说明:
- 开发工具:IDEA 2024.1.7
- JDK版本: JDK 17
- Spring Boot版本:2.7.3
- Maven版本:3.9.6
- 操作系统:Windows 11
1.什么是Knife4j?
Knife4j 是一个为 Java 项目生成和管理 API 文档的工具。实际上,它是 Swagger UI 的一个增强工具集,旨在让 Swagger 生成的 API 文档更优雅、更强大。 Knife4j支持在线调试,可以节省很多时间。
- 美观的 UI:相比于原生 Swagger UI,Knife4j 提供了更加人性化和美观的界面设计。
- 丰富的文档交互功能:支持在线调试、请求参数动态输入、接口排序等。
- 个性化配置:可自定义 API 文档的界面风格,实现文档界面的个性化展示。
2.要使用这个工具只需要两步
1.导入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
2.编写配置文件
package com.knife4jtest.config;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Configuration //标志着这是一个配置类
@EnableSwagger2WebMvc
public class SwaggerConfig {
// http://localhost:8881/doc.html#/home
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.knife4jtest.controller"))//对应你controller目录
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger 接口文档") //指定文档标题
.contact(new Contact("作者名字", "url", "你的邮箱")) //指定作者
.description("swagger接口文档描述") //接口文档描述
.license("Apache License Version 2.0") //许可
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html") //许可链接
.termsOfServiceUrl("http://localhost:8081") //指定在线接口文档访问url
.version("1.0") //指定版本号
.build();
}
}
对应的接口和要扫描的包需要修改成你项目中对应的
这里的controller目录是com.knife4jtest.controller
http://localhost:8081对应的是你的项目入口地址,这里是8081改成你自己的
3.工具的接口地址
http://localhost:8081/doc.html#/home

4.下面是这个工具的常用注解
|
作用范围 |
API |
API常用参数 |
作用位置 |
|
协议集描述 |
@Api |
@Api(tags = {"tag1","tag2","..."}) |
controller类 |
|
协议描述 |
@ApiOperation |
@ApiOperation(value = "功能描述",notes = "备注") |
controller类的方法 |
|
描述返回对象的意义 |
@ApiModel |
@ApiModel(value="类名",description="类描述") |
返回对象类 |
|
对象属性 |
@ApiModelProperty |
@ApiModelProperty(value = "类属性描述",required = true,example = "属性举例",notes = "备注") |
出入参数对象的字段 |
|
非对象参数集 |
@ApiImplicitParams |
@ApiImplicitParams({@ApiImplicitParam(),@ApiImplicitParam(),...}) |
controller的方法 |
|
非对象参数描述 |
@ApiImplicitParam |
@ApiImplicitParam(name = "参数名",value = "参数描述",required = true,paramType = "接口传参类型",dataType = "参数数据类型") |
@ApiImplicitParams的方法里用 |
|
Response集 |
@ApiResponses |
@ApiResponses({ @ApiResponse(),@ApiResponse(),..}) |
controller的方法 |
|
Response |
@ApiResponse |
@ApiResponse(code = 10001, message = "返回信息") |
@ApiResponses里用 |
|
忽略注解 |
@ApiIgnore |
@ApiIgnore |
类,方法,方法参数 |
5.下面给出一个演示案例
controller类
package com.weblog.controller;
import com.weblog.entity.User;
import com.weblog.common.Result;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@Api(tags = {"用户管理", "用户操作"}) // 支持多个tag
@RestController
@RequestMapping("/api/user")
public class UserController {
@ApiOperation(value = "查询用户信息", notes = "根据用户ID查询详细信息,返回用户对象")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true,
paramType = "path", dataType = "Long", example = "1001"),
@ApiImplicitParam(name = "version", value = "API版本", required = false,
paramType = "header", dataType = "String", defaultValue = "v1")
})
@ApiResponses({
@ApiResponse(code = 200, message = "查询成功"),
@ApiResponse(code = 404, message = "用户不存在"),
@ApiResponse(code = 500, message = "服务器内部错误")
})
@GetMapping("/{id}")
public Result<User> getUserById(@PathVariable Long id) {
// 业务逻辑
return Result.success(new User());
}
@ApiOperation(value = "创建用户", notes = "新增用户信息")
@ApiResponses({
@ApiResponse(code = 10001, message = "用户名已存在"),
@ApiResponse(code = 10002, message = "邮箱格式错误")
})
@PostMapping("/create")
public Result<String> createUser(@RequestBody User user) {
// 业务逻辑
return Result.success("创建成功");
}
@ApiOperation(value = "删除用户", notes = "根据ID删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true,
paramType = "query", dataType = "Long", example = "1001")
@DeleteMapping("/delete")
public Result<String> deleteUser(@RequestParam Long id) {
// 业务逻辑
return Result.success("删除成功");
}
@ApiIgnore // 忽略此接口,不在文档中显示
@GetMapping("/internal")
public String internalMethod() {
return "内部方法";
}
}
实体类
package com.weblog.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
@ApiModel(value = "用户实体", description = "用户基本信息对象")
public class User {
@ApiModelProperty(value = "用户唯一标识", required = true, example = "1001", notes = "自增主键")
private Long id;
@ApiModelProperty(value = "用户名", required = true, example = "zhangsan", notes = "3-20位字符")
private String username;
@ApiModelProperty(value = "邮箱地址", required = true, example = "zhangsan@example.com", notes = "用于登录")
private String email;
@ApiModelProperty(value = "手机号码", required = false, example = "13800138000", notes = "11位数字")
private String phone;
@ApiModelProperty(value = "用户年龄", required = false, example = "25", notes = "1-120岁")
private Integer age;
@ApiModelProperty(value = "创建时间", required = true, example = "2024-01-15 10:30:00", notes = "自动生成")
private Date createTime;
// getter/setter 方法
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; }
}
通用返回结果类
package com.weblog.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "统一响应结果", description = "所有接口的通用返回格式")
public class Result<T> {
@ApiModelProperty(value = "状态码", required = true, example = "200", notes = "200成功,其他失败")
private Integer code;
@ApiModelProperty(value = "返回消息", required = true, example = "操作成功")
private String message;
@ApiModelProperty(value = "返回数据", notes = "具体业务数据")
private T data;
public Result(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
// getter/setter
public Integer getCode() { return code; }
public void setCode(Integer code) { this.code = code; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public T getData() { return data; }
public void setData(T data) { this.data = data; }
}
6252

被折叠的 条评论
为什么被折叠?



