Knife4j actual combat

Published 2026-07-30 19:37 Updated 2026-10-13 17:14 2498 words 13 min read ... Page views AI-reviewed An AI proof-read this post, but it still deserves a careful read. AI-rewritten Someone else wrote the original; AI helped me rewrite and polish it.

AI-reviewed An AI proof-read this post, but it still deserves a careful read.

The article introduces the entire process of integrating Knife4j in the Spring Boot 3 project, emphasizing that Knife4j is an interface document enhancement tool based on the OpenAPI 3 specification. It generates documents through the springdoc-openapi and provides visual display and online debugging functions in conjunction with Swagger UI. It focuses on environment configuration, annotation use, security control, document export and troubleshooting of common problems. It points out that the Jakarta version of Knife4j Starter should be used correctly, scan packages and groups should be reasonably configured, and interface document access should be opened or restricted in the development and production environments respectively., clearly distinguish between interface concealment and privilege protection to ensure document security and functional integrity.

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 describing the RESTful API.
  • springdoc-openapi: Scan the Spring Web interface and generate OpenAPI 3 documentation.
  • Swagger UI: A common Web interface for displaying and debugging OpenAPI documentation.
  • Knife4j: Provides enhanced interfaces and extensions 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 based on springdoc-openapi Provide.

Main differences between Spring Boot 2 and Spring Boot 3

comparison itemSpring Boot 2 Common SolutionsSpring Boot 3 Recommended Solutions
Java versionYou can usually use JDK 8 or later, depending on the Spring Boot versionMinimum JDK 17 is required
Java EE package namemainly used javax.*migrate to jakarta.*
Interface document specificationYou can use OpenAPI 2 or OpenAPI 3Recommended use of OpenAPI 3
common implementationSpringfox or springdoc-openapispringdoc-openapi
Knife4j StarterSelect the corresponding Starter based on the specification and framework versionUse Jakarta version of OpenAPI 3 Starter
Common NotesOld 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. migrate to springdoc-openapi Later, the old annotations should be replaced with OpenAPI 3 annotations.

Common enhancements to Knife4j over Swagger UI

comparison itemSwagger UIKnife4j
page displayProvides standard OpenAPI documentation interfaceProvides an enhanced interface that is more suitable for Chinese projects
interface commissioningSupport sending requests onlineEnhance parameter filling, request debugging and result display
interface to retrieveSupport basic filteringProvides enhanced features such as interface search
document is exportedA complete offline export process is not provided by defaultSupport exporting Markdown, HTML, Word and OpenAPI documents
extended configurationUsing Swagger UI configuration itemsAdditional enhanced Knife4j configuration
access protectionUsually you need to integrate your own security frameworkProvide auxiliary configurations such as production protection and Basic certification

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_cn

Configuration instructions:

  • springdoc.api-docs.path The JSON document address used to configure OpenAPI.
  • springdoc.group-configs Used to configure document grouping, interface paths, and controller scan packages.
  • packages-to-scan Must be replaced with the actual controller package name for the current project.
  • knife4j.enable Used to turn on Knife4j enhancements.
  • knife4j.setting.language Used to set the interface language.

Basic information of configuration interface document

by declaring OpenAPI Bean 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.

doc.html Troubleshooting order when access is inaccessible

Under normal circumstances, there is no need to manually configure static resource mappings after the introduction of Starter. if there is 404、401 or 403, should be checked in the following order:

  1. Check whether the Maven dependency uses the Jakarta Starter corresponding to Spring Boot 3.

  2. Check if the project mistakenly introduced multiple versions of the springdoc-openapi or Springfox.

  3. check packages-to-scan Whether it is the real controller package path.

  4. Check if the project is used @EnableWebMvc, or whether it has completely taken over the Spring MVC configuration.

  5. Check whether Spring Security blocks document pages and OpenAPI document interfaces.

  6. Check whether the app is configured context-path, whether a context path needs to be added to the access address.

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

functionOld Swagger 2 annotationsOpenAPI 3 annotations
controller grouping@Api@Tag
API description@ApiOperation@Operation
parameter description@ApiParam、@ApiImplicitParam@Parameter
Description of multiple parameters@ApiImplicitParams@Parameters
model specification@ApiModel@Schema
field description@ApiModelProperty@Schema
Hide interfaces or classes@ApiIgnore@Hidden or @Operation(hidden = true)

use @Schema Describe entity classes

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 be accessed through @Data Streamline Getter and Setter, but make sure that the project has correctly introduced Lombok and enabled annotation processing.

use @Tag and @Operation Description controller

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 configuration below is the front OpenAPI An upgraded version of the Bean, only one remains in the actual project OpenAPI Bean:

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 the JWT, the debugging request will be carried according to the Bearer authentication method Authorization Request header.

note: Add security solutions to OpenAPI Object representation documentation requires authentication by default, but it does 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 Controller or interface can be hidden:

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 It 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: true

Among them:

  • knife4j.production Used to start Knife4j’s production environmental protection strategy.
  • springdoc.api-docs.enabled Used to turn off the OpenAPI JSON interface.
  • springdoc.swagger-ui.enabled Used to close 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. Example Using environment variables KNIFE4J_PASSWORD Inject the 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:

  • packages-to-scan Whether the configuration is correct.
  • Whether the controller is used @RestController。
  • Whether the request method uses @GetMapping、@PostMapping Wait for mapping annotations.
  • Whether the controller is within Spring Boot’s default scan range.
  • Is it incorrectly configured? paths-to-match。

Document page return 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.

Document page return 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 to use @EnableWebMvc Overrides automatic configuration.
  • 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 old versions io.swagger.annotations and OpenAPI 3 annotations.

The document has not changed after modifying the interface

You can try in turn:

  1. Verify that the code has been recompiled and restart the application.

  2. Refresh the browser page.

  3. Clear Knife4j page cache.

  4. Check that what is currently viewed is correctly grouped.

  5. direct access to /v3/api-docs, 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:

  1. Use JDK 17 or later.

  2. Introducing Jakarta version of Knife4j OpenAPI 3 Starter.

  3. by springdoc Configure scan package, grouping, and OpenAPI document paths.

  4. by OpenAPI Bean sets basic document information and authentication scheme.

  5. use @Tag、@Operation、@Parameter and @Schema Describe the interface.

  6. Open documents in the development environment and close or restrict access in the production environment according to security requirements.

  7. Clearly distinguish between “hidden interface documents” and “protecting real interfaces”, and cannot be used @Hidden As a means of authority control.

Written by AI-rewritten

If you enjoyed this, leave a comment~

Loading...