knife4j简介
接口文档工具,主要用于提升 Spring Boot 项目中接口文档的展示效果和用户体验。它由中国开发者维护,广泛用于国内企业级开发。
knife4j-spring-boot-starter
基于 Swagger 和 Springfox 的增强型文档生成工具
默认已经集成了 springfox-swagger2,不需要再手动添加。
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
启用 Knife4j:
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xgss.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("API DOC").build();
}
}
访问:http://localhost:8080/doc.html
问题:
若你使用的是 Spring Boot 2.6+,可能会遇到与 springfox 相关的兼容性问题(如空指针异常),建议升级到 springdoc-openapi 或使用适配方案。
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
适配方案:添加配置,该配置用于指定 Spring MVC 的路径匹配策略为 AntPathMatcher(基于 Ant 风格的路径匹配),从 Spring Boot 2.6 开始,默认的PathPatternParser: URL 路径匹配器由(性能更高、更现代)
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
如果你需要 OpenAPI 3 支持,请考虑使用 knife4j-openapi3。
knife4j-openapi3-spring-boot-starter
是基于 OpenAPI 3 规范的 Knife4j 版本,兼容 Spring Boot 2.6+,基于 springdoc-openapi 实现,不再依赖已停止维护的 springfox。
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
配置文件
knife4j:
enable: true
production: false # 是否开启生产环境屏蔽文档访问
basic:
enable: false # 是否开启基础认证
username: admin
password: 123456
地址:http://localhost:8080/doc.html
OpenAPI 3 注解说明
注解使用OpenAPI 3 的注解,注解代码位于 io.swagger.v3.oas.annotations 包里。文档:https://openapi.apifox.cn/
swagger2 | swagger3 | 说明 |
@Api | @Tag 或者 Tags | 用于类上,方法上 |
@ApiIgnore | @Parameter(hidden = true) 或 @Operation(hidden = true) 或 @Hidden | |
@ApiImplicitParam | @Parameter | |
@ApiImplicitParams | @Parameters | |
@ApiModel | @Schema | 用于描述实体类属性的描述、示例、验证规则等 |
@ApiOperation(value = “foo”, notes = “bar”) | @Operation(summary = “foo”, description = “bar”) | |
@ApiParam | @Parameter | |
@ApiResponse(code = 404, message = “foo”) | @ApiResponse(responseCode = “404”, description = “foo”) | |
@OpenAPIDefinition
用于定义整个API文档的基本信息,通常应用于类或接口。
- openapi:这是 OpenAPI 规范的版本,通常是 "3.0.x"。
- info:这是一个 Info 对象,用于描述 API 的基本信息,如标题、版本和描述。
- servers:这是一个 Server 对象的数组,描述了 API 服务器的相关信息。
- externalDocs:这是一个 ExternalDocumentation 对象,用于描述外部文档的位置。
- security:这是一个安全要求对象的数组,描述了 API 的安全需求。
- tags:这是一个 Tag 对象的数组,用于为 API 的操作提供分组和描述。
- extensions:这是一个额外的属性集合,用于提供不在 OpenAPI 规范中定义的额外信息。
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.servers.Server;
@OpenAPIDefinition(
openapi = "3.0.3",
info = @Info(
title = "My API",
version = "1.0.0",
description = "This is my first API using Swagger 3"
),
servers = {
@Server(url = "http://localhost:8080/api", description = "Local development server")
}
)
public class MyApiDefinition {
// API 的其他定义和配置
}
@Info
在 Swagger 3 中,Info 注解用于描述 API 文档的基本信息。它是 OpenAPIDefinition 注解中 info 属性的值,用于为 API 提供元数据,如标题、版本、描述等。
title:API 的标题或名称。这通常是 API 的简短描述,用于在文档中标识和区分不同的 API。
version:API 的版本。这有助于区分 API 的不同迭代,并允许使用者了解他们正在使用的是哪个版本的 API。
description:API 的详细描述。这可以是一个较长的文本,用于解释 API 的目的、功能、使用方式等。它是对标题和版本的补充,提供了更详细的信息。
termsOfService:API 的服务条款。这是一个 URL,指向包含 API 使用条款和条件的页面。这有助于确保 API 的使用者了解并遵守相关的使用规定。
contact:API 的联系信息。这可以是一个 Contact 对象,包含姓名、URL 和电子邮件地址,用于提供 API 的支持或反馈渠道。
license:API 的许可信息。这是一个 License 对象,描述了 API 的许可类型(如 Apache 2.0)和许可 URL(如指向许可详细信息的页面)。
extensions:额外的属性集合,用于提供不在 OpenAPI 规范中定义的额外信息。这允许你添加自定义的元数据到 API 文档中。
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.info.License;
import io.swagger.v3.oas.annotations.info.Contact;
@OpenAPIDefinition(
info = @Info(
title = "My API",
version = "1.0.0",
description = "This is a description of my API",
termsOfService = "http://example.com/terms",
contact = @Contact(
name = "API Support",
url = "http://example.com/support",
email = "[email protected]"
),
license = @License(
name = "Apache 2.0",
url = "http://www.apache.org/licenses/LICENSE-2.0.html"
)
)
)
public class MyApiDefinition {
// API 的其他定义和配置
}
@Operation
描述 API 操作的元数据信息。常用于 controller 上
部分参数:
- summary:简短描述
- description :更详细的描述
- hidden:是否隐藏
- tags:标签,用于分组API
- operationId:操作的唯一标识符,建议使用唯一且具有描述性的名称
- parameters:指定相关的请求参数,使用 @Parameter 注解来定义参数的详细属性。
- requestBody:指定请求的内容,使用 @RequestBody 注解來指定请求的类型。
- responses:指定操作的返回内容,使用 @ApiResponse 注解定义返回值的详细属性。
- deprecated:标记操作是否已弃用。
- security:操作的安全要求。
- externalDocs:外部文档的链接。
@Operation(
summary = "操作摘要",
description = "操作的详细描述",
operationId = "operationId",
tags = "tag1",
parameters = {
@Parameter(name = "param1", description = "参数1", required = true),
@Parameter(name = "param2", description = "参数2", required = false)
},
requestBody = @RequestBody(
description = "请求描述",
required = true,
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = RequestBodyModel.class)
)
),
responses = {
@ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseModel.class))),
@ApiResponse(responseCode = "400", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseModel.class)))
}
)
@Tag(name = "标签1")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseModel.class))),
@ApiResponse(responseCode = "400", description = "錯誤", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseModel.class)))
})
public void Operation() {
// 逻辑
}
@Schema
可以应用于类或字段上
name:名称
title:标题
description:描述
example:示例值
required:是否为必须
format:属性的格式。如 @Schema(format = “email”)
maxLength 、 minLength:指定字符串属性的最大长度和最小长度
maximum 、 minimum:指定数值属性的最大值和最小值
pattern:指定属性的正则表达式模式
type: 数据类型(integer,long,float,double,string,byte,binary,
boolean,date,dateTime,password),必须是字符串。
如 @Schema=(type=“integer”)
items:指定数组元素的类型
properties:指定对象的字段。
additionalProperties:指定对象是否允许包含其他属性。
implementation :具体的实现类,可以是类本身,也可以是父类或实现的接口
@Tag(name = "用户", description = "用户实体类")
@Data
public class User {
@Schema(name = "用户id", type = "long")
private Long id;
@Schema(name = "用户名", type = "long")
private String name;
@Schema(name = "密码", type = "password")
private String password;
}
@Parameter
用于描述 API 操作中的参数
name : 指定的参数名
in:参数来源,可选 query、header、path 或 cookie,默认为空,表示忽略
- ParameterIn.QUERY 请求参数
- ParameterIn.PATH 路径参数
- ParameterIn.HEADER header参数
- ParameterIn.COOKIE cookie 参数
- description:参数描述
required:是否必填,默认为 false
description: 参数的描述。这个描述将在 API 文档中显示,以帮助用户理解参数的用途和期望的值。
deprecated:布尔值,指示参数是否已弃用。如果设置为 true,则在 API 文档中会显示该参数已弃用的标记。
allowEmptyValue: 布尔值,指示是否允许空值。默认为 false。
example : 参数的示例值。这将在 API 文档中显示,以便用户了解如何提供参数值。
examples : 提供多个示例值的映射,可以用来展示不同情况下的参数值。
hidden : 布尔值,指示参数是否在 API 文档中隐藏。默认为 false。
schema :参数的数据类型。如 schema = @Schema(type = “string”)
@Operation(summary = "根据用户名查询用户列表")
@GetMapping("/query/{username}")
public List<User> queryUserByName(@Parameter(name = "username", in = ParameterIn.PATH, description = "用户名",
required = true) @PathVariable("username") String userName) {
return new ArrayList<>();
}
@Parameters
用于描述操作的输入参数,包含多个 @Parameter 注解,指定多个参数。
@Parameters({
@Parameter(
name = "param1",
description = "description",
required = true,
in = ParameterIn.PATH,
schema = @Schema(type = "string")
),
@Parameter(
name = "param2",
description = "description",
required = true,
in = ParameterIn.QUERY,
schema = @Schema(type = "integer")
)
})
@Tag
用于为 API 操作添加标签,为 API 的操作进行分组
name:标签的名称,用于在 API 文档中标识和分组操作。
description:对标签的描述,提供关于该组操作的额外信息。
externalDocs:一个 ExternalDocumentation 对象,用于提供指向外部文档的链接,这些文档可能包含有关该标签的更多详细信息。
import io.swagger.v3.oas.annotations.tags.Tag;
@RestController
@RequestMapping("/users")
@Tag(name = "User Management", description = "Endpoints for managing user information")
public class UserController {
// User-related endpoints here
}
@RestController
@RequestMapping("/orders")
@Tag(name = "Order Processing", description = "Endpoints for order placement, tracking, and management")
public class OrderController {
// Order-related endpoints here
}
@ApiResponses
用于定义 API 操作的可能响应。这个注解可以应用于方法上,以便为该操作的所有可能响应提供详细的描述。@ApiResponses 注解包含一个或多个 @ApiResponse 注解,每个 @ApiResponse 描述一个特定的响应状态码及其相关信息。
value (必需): 一个 @ApiResponse 数组,每个元素描述一个特定的响应。
@ApiResponse 注解的属性:
responseCode (必需): HTTP 状态码,表示响应的 HTTP 状态。
description (必需): 对响应的简短描述。
content (可选): 一个 MediaType 对象数组,描述响应的内容类型(例如,JSON 或 XML)和模式(例如,使用 @Schema 引用的模型)。
headers (可选): 一个 Parameter 对象数组,描述响应头的信息。
@ApiOperation("Get a list of users")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successful operation"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "Resource not found")
})
@GetMapping("/users")
public ResponseEntity<List<User>> getUsers() {
// ... 实现逻辑 ...
}
示例:
@RestController
@Tag(name= "用户操作接口",description = "用户的增删改查操作之类")
@RequestMapping("/user")
public class UserController {
@Operation(summary = "根据id查询user")
@GetMapping("/query/{id}")
public String queryById(@PathVariable("id") String id){
return id;
}
}
@ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = User.class)))
@ApiResponse(responseCode = "404", description = "查询失败")
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
// ...
}