Knife4j actual combat
Knife4j core cognition
What is Knife4j
Knife4j is an interface document enhancement solution for Java Web projects. It can read OpenAPI documents generated by applications and provides more easy-to-use interface display, online debugging, search, sorting, offline export and access control functions.
In a Spring Boot 3 project, the related components can be understood as the following relationships:
- OpenAPI 3: A specification that describes RESTful APIs.
- springdoc-openapi: Scan the Spring Web interface and generate OpenAPI 3 documentation.
- Swagger UI: A common Web interface for displaying and debugging OpenAPI documents.
- Knife4j: Provides enhanced interface and extensibility based on OpenAPI documentation.
Therefore, Knife4j is not a new interface specification, nor is it equivalent to OpenAPI 3. For Spring Boot 3 projects, Knife4j’s underlying document generation capabilities are mainly provided by springdoc-openapi.
Main differences between Spring Boot 2 and Spring Boot 3
| Comparison Items | Spring Boot 2 Common Solutions | Spring Boot 3 Recommended Solutions |
|---|---|---|
| Java version | can usually use JDK 8 or later, depending on Spring Boot version | requiring a minimum JDK 17 |
| Java EE package name | mainly uses javax.* | to migrate to jakarta.* |
| Interface Documentation Specification | can use OpenAPI 2 or OpenAPI 3 | Recommended use OpenAPI 3 |
| Common implementations of | Springfox or springdoc-openapi | |
| Knife4j Starter | Select corresponding Starter | based on specification and framework version Use Jakarta version of OpenAPI 3 Starter |
| Common Notes | Old projects may use io.swagger.annotations.* | Use io.swagger.v3.oas.annotations.* |
Note: It’s not that Spring Boot 3 itself “abandons Swagger 2 annotations,” but that Spring Boot 3 projects often no longer use older Springfox-based solutions. After migrating to springdoc-openapi, old annotations should be replaced with OpenAPI 3 annotations.
Common enhancements to Knife4j over Swagger UI
| Comparison Items | Swagger UI | Knife4j |
|---|---|---|
| page shows | provides a standard OpenAPI document interface | provides an enhanced interface more suitable for Chinese projects |
| interface debugging | supports online sending of requests | enhances parameter filling, request debugging and result display |
| Interface search | supports basic filtering | provides enhanced functions such as interface search |
| Document Export | does not provide a complete offline export process by default. | supports exporting Markdown, HTML, Word and OpenAPI documents |
| Extended Configuration | Use Swagger UI Configuration Item | Additional Knife4j Enhanced Configuration |
| Access Protection | usually needs to combine its own security framework processing | provides production protection and Basic certification and other auxiliary configurations |
applicable scenarios
- Interface documents are automatically generated and maintained in front and back separation projects.
- The interface is called online during the development and testing phases.
- Display request parameters, response structure, status code, and field descriptions.
- Unified management of interface documents in multiple module or microservice projects.
- Export the interface document for delivery or archiving.
Spring Boot 3 integrates Knife4j
environmental requirements
The examples in this article use the following environment:
- JDK 17 or later.
- Spring Boot 3.x。
- Project Maven.
spring-boot-starter-web。- Knife4j 4.5.0。
In actual projects, dependency compatibility should be checked based on the specific version of Spring Boot. Don’t judge that components are compatible just by “higher version”.
Introducing Maven dependencies
Spring Boot 3 uses Jakarta version of Knife4j Starter:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>
The Starter already integrates the springdoc-openapi related dependencies required by OpenAPI 3. There is usually no need to introduce Springfox, Swagger 2, or other versions of the springdoc-openapi separately, otherwise dependency conflicts may arise.
Configure application.yml
Here is a basic configuration suitable for a single module project:
server:
port: 8080
spring:
application:
name: knife4j-spring-boot3-demo
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /v3/api-docs
group-configs:
- group: default
paths-to-match: /**
packages-to-scan: com.example.knife4jdemo.controller
knife4j:
enable: true
setting:
language: zh_cnConfiguration instructions:
springdoc.api-docs.pathis used to configure OpenAPI JSON document addresses.springdoc.group-configsis used for configuration document grouping, interface paths and controller scanning packages.packages-to-scanmust be replaced with the actual controller package name of the current project.knife4j.enableis used to turn on Knife4j enhancements.knife4j.setting.languageis used to set the interface language.
Basic information of configuration interface document
By declaring OpenAPI Bean, you can uniformly set the document title, version, description and contact information:
package com.example.knife4jdemo.config;
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 org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Knife4jOpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("用户管理系统接口文档")
.version("1.0.0")
.description("基于 Spring Boot 3、OpenAPI 3 和 Knife4j 构建的接口文档")
.contact(new Contact()
.name("项目开发组")
.email("demo@example.com"))
.license(new License()
.name("Apache 2.0")));
}
}Start the project and access documents
After starting the Spring Boot project, visit:
http://localhost:8080/doc.html
The default access address for OpenAPI JSON documents is /v3/api-docs. If grouping is configured, corresponding grouping document addresses may also be generated.
Troubleshooting sequence when doc.html cannot be accessed
Under normal circumstances, there is no need to manually configure static resource mappings after the introduction of Starter. If 404, 401 or 403 occurs, check it in the following order:
-
Check whether the Maven dependency uses the Jakarta Starter corresponding to Spring Boot 3.
-
Check if the project mistakenly introduced multiple versions of the springdoc-openapi or Springfox.
-
Check whether
packages-to-scanis the real controller package path. -
Check whether the project uses
@EnableWebMvcor has completely taken over the Spring MVC configuration. -
Check whether Spring Security blocks document pages and OpenAPI document interfaces.
-
Check whether the application is configured with
context-pathand whether the access address needs to add a context path.
Consider supplementing resource mappings only if the project does customize static resource rules and confirms that automatic configuration has not taken effect:
package com.example.knife4jdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}This configuration is a troubleshooting solution and is not a fixed requirement for all Spring Boot 3 projects.
Common OpenAPI 3 annotations
Compare old annotations with new annotations
| Features | Old Swagger 2 Notes | OpenAPI 3 Notes |
|---|---|---|
| Controller Group | @Api | @Tag |
| Interface Description | @ApiOperation | @Operation |
| Parameter Description | @ApiParam, @ApiImplicitParam | @Parameter |
| Multiple parameter descriptions | @ApiImplicitParams | @Parameters |
| Model Description | @ApiModel | @Schema |
| Field Descriptions | @ApiModelProperty | @Schema |
| hidden interface or | @ApiIgnore | @Hidden or @Operation(hidden = true) |
Describing entity classes using @Schema
package com.example.knife4jdemo.domain;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "用户信息")
public class User {
@Schema(
description = "用户主键",
requiredMode = Schema.RequiredMode.REQUIRED,
example = "10001"
)
private Long id;
@Schema(
description = "用户名",
requiredMode = Schema.RequiredMode.REQUIRED,
example = "zhangsan"
)
private String username;
@Schema(
description = "手机号码",
requiredMode = Schema.RequiredMode.REQUIRED,
example = "13800138000"
)
private String phone;
@Schema(description = "年龄", example = "26")
private Integer age;
@Schema(description = "用户状态:0 表示禁用,1 表示正常", example = "1")
private Integer status;
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 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 Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}Projects that use Lombok can simplify Getter and Setter with @Data, but you need to ensure that the project has correctly introduced Lombok and enabled annotation processing.
Describing the controller using @Tag and @Operation
package com.example.knife4jdemo.controller;
import com.example.knife4jdemo.domain.User;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "提供用户查询接口")
public class UserController {
@GetMapping("/{id}")
@Operation(
summary = "根据编号查询用户",
description = "根据用户主键查询用户详细信息"
)
public User getUserById(
@Parameter(
description = "用户主键",
required = true,
example = "10001"
)
@PathVariable("id") Long id
) {
User user = new User();
user.setId(id);
user.setUsername("zhangsan");
user.setPhone("13800138000");
user.setAge(26);
user.setStatus(1);
return user;
}
@GetMapping
@Operation(
summary = "查询用户列表",
description = "查询当前系统中的用户数据"
)
public List<User> listUsers() {
return List.of(getUserById(10001L));
}
}Visit after restarting the project:
http://localhost:8080/doc.html
The page should display user management groups, interface summaries, parameter descriptions and response models.
Knife4j Advanced Features
Configure global JWT certification
For projects that use JWT, you can declare the HTTP Bearer authentication scheme in the OpenAPI documentation. The following configuration is an upgraded version of the previous OpenAPI Bean. Only one OpenAPI Bean is retained in the actual project:
package com.example.knife4jdemo.config;
import io.swagger.v3.oas.models.Components;
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 io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Knife4jOpenApiConfig {
private static final String SECURITY_SCHEME_NAME = "BearerAuth";
@Bean
public OpenAPI customOpenAPI() {
SecurityScheme securityScheme = new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.description("输入登录后获得的 JWT");
return new OpenAPI()
.info(new Info()
.title("用户管理系统接口文档")
.version("1.0.0")
.description("支持 JWT 调试的接口文档")
.contact(new Contact()
.name("项目开发组")
.email("demo@example.com"))
.license(new License()
.name("Apache 2.0")))
.components(new Components()
.addSecuritySchemes(SECURITY_SCHEME_NAME, securityScheme))
.addSecurityItem(new SecurityRequirement()
.addList(SECURITY_SCHEME_NAME));
}
}After the configuration is completed, the authentication entry will be displayed on the document page. After the developer enters JWT, the debugging request will carry the Authorization request header according to the Bearer authentication method.
Note: Adding a security scheme to the OpenAPI object representation document requires authentication by default, but it will not replace Spring Security’s server-side authentication logic.
Export offline documents
Knife4j’s document management feature can export the following:
- Markdown documentation.
- Offline HTML document.
- Word document.
- Original OpenAPI JSON document.
Knife4j’s official export function does not directly generate PDFs. When you need PDF, you can export Markdown or HTML first, and then use other tools to convert it to PDF.
Hide interfaces that don’t need to be exposed
Use @Hidden to hide the controller or interface:
package com.example.knife4jdemo.controller;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Hidden
@RestController
@RequestMapping("/admin")
public class AdminController {
@PostMapping("/password")
public String updatePassword() {
return "密码修改成功";
}
}You can also hide only a single method:
@Hidden
@PostMapping("/internal/reset")
public String resetData() {
return "重置成功";
}
Important note: @Hidden only controls whether the interface appears in the OpenAPI document and does not prevent clients from accessing the interface. Sensitive interfaces must still be protected through Spring Security, privilege verification, and gateway policies.
Production environment safety configuration
Development environment configuration
The development environment can open the interface document:
knife4j:
enable: true
production: false
Production Environment Closure Documents
The production environment can turn off the Knife4j page, Swagger UI, and OpenAPI JSON interface at the same time:
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false
knife4j:
enable: false
production: trueAmong them:
knife4j.productionis used to activate Knife4j’s production environmental protection strategy.springdoc.api-docs.enabledis used to turn off the OpenAPI JSON interface.springdoc.swagger-ui.enabledis used to turn off the Swagger UI.
Whether to completely disable interface documents in the production environment should be decided based on the project’s network isolation, authority model and operation and maintenance requirements.
Protect documents with Basic certification
When an internal test environment does require open documentation, you can enable Basic certification:
knife4j:
enable: true
production: false
basic:
enable: true
username: doc_user
password: ${KNIFE4J_PASSWORD}
Don’t save real passwords directly in the code warehouse. The example uses the environment variable KNIFE4J_PASSWORD to inject a password.
Basic certification can only be used as part of document access protection. Production systems should also incorporate measures such as HTTPS, network access control, Spring Security and unified identity authentication.
common problems
The page can be opened but has no interface
Key inspections:
- Whether the
packages-to-scanis configured correctly. - Whether the controller uses
@RestController. - Whether the request method uses mapping annotations such as
@GetMappingand@PostMapping. - Whether the controller is within Spring Boot’s default scan range.
- Whether
paths-to-matchis incorrectly configured.
Documentation page returns to 401 or 403
This usually means that the request was intercepted by a security filter. The following resources need to be released on demand in the development environment:
/doc.html/webjars/**/v3/api-docs/**/swagger-ui/**/swagger-ui.html
Whether and how to release it depends on the Spring Security version and permission policy actually used by the project.
Documentation page back to 404
Key inspections:
- Whether the Starter was chosen correctly.
- Depends on whether the download is successful.
- Whether there is a dependency conflict.
- Whether the application context path is configured.
- Whether automatic configuration is overridden with
@EnableWebMvc. - Whether the static resource mapping has been customized.
Comments not displayed in document
Check whether the annotation guide package comes from io.swagger.v3.oas.annotations. Don’t mix older versions of io.swagger.annotations and OpenAPI 3 annotations.
The document has not changed after modifying the interface
You can try in turn:
-
Verify that the code has been recompiled and restart the application.
-
Refresh the browser page.
-
Clear Knife4j page cache.
-
Check that what is currently viewed is correctly grouped.
-
Directly visit
/v3/api-docsto confirm whether the OpenAPI JSON generated by the backend has been updated.
summary
The core process for Spring Boot 3 to integrate Knife4j is as follows:
-
Use JDK 17 or later.
-
Introducing Jakarta version of Knife4j OpenAPI 3 Starter.
-
Configure scan package, grouping, and OpenAPI document paths through
springdoc. -
Set up basic document information and certification scheme through
OpenAPIBean. -
Use
@Tag,@Operation,@Parameter, and@Schemato describe the interfaces. -
Open documents in the development environment and close or restrict access in the production environment according to security requirements.
-
Clearly distinguish between “hidden interface documents” and “protecting real interfaces”, and
@Hiddencannot be used as a means of authority control.
If you enjoyed this, leave a comment~