### Install Knife4x Go module Source: https://knife4jnext.com/knife4x Use the go get command to add the Knife4x dependency to your project. ```bash go get github.com/songxychn/knife4j-next/knife4x/go@v0.2.1 ``` -------------------------------- ### Implement Example Controller Source: https://knife4jnext.com/guide/getting-started Use OpenAPI annotations to document REST endpoints within a Spring Boot controller. ```java import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/users") @Tag(name = "用户管理", description = "用户相关接口") public class UserController { @Operation(summary = "按 id 查询用户") @GetMapping("/{id}") public UserDto get(@PathVariable Long id) { return new UserDto(id, "alice"); } @Operation(summary = "新增用户") @PostMapping public UserDto create(@RequestBody UserDto body) { return body; } } ``` -------------------------------- ### Reactive Controller Example Source: https://knife4jnext.com/guide/webflux A sample Spring WebFlux controller using OpenAPI annotations. ```java import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; @RestController @RequestMapping("/api/users") @Tag(name = "用户管理") public class UserController { @Operation(summary = "按 id 查询用户") @GetMapping("/{id}") public Mono get(@PathVariable Long id) { return Mono.just(new UserDto(id, "alice")); } } ``` -------------------------------- ### Verify Aggregation Service Source: https://knife4jnext.com/guide/aggregation Commands to start the application and verify the aggregation endpoint and resource list. ```bash # 启动聚合应用 mvn spring-boot:run -f aggregation-app/pom.xml # 访问聚合入口 curl -I http://localhost:8080/doc.html # 查看聚合的分组列表(开发调试) curl http://localhost:8080/swagger-resources ``` -------------------------------- ### Selection Decision Tree Source: https://knife4jnext.com/reference/compatibility A visual guide to selecting the appropriate Knife4j starter based on Spring Boot version and application type. ```text 你的 Spring Boot 版本是? ├── 2.x │ ├── 需要继续用 Swagger 2 / Springfox? │ │ └── knife4j-openapi2-spring-boot-starter(Vue 3 UI) │ └── 用 OpenAPI 3 / springdoc? │ ├── WebMvc → knife4j-openapi3-spring-boot-starter(React UI) │ └── WebFlux → knife4j-openapi3-webflux-spring-boot-starter(React UI) ├── 3.x │ ├── WebMvc → knife4j-openapi3-jakarta-spring-boot-starter(React UI) │ ├── WebFlux → knife4j-openapi3-webflux-jakarta-spring-boot-starter(React UI) │ └── Spring Cloud Gateway? │ ├── WebFlux → knife4j-gateway-spring-boot-starter │ └── Server Web MVC(Boot 3.5)→ knife4j-gateway-webmvc-spring-boot-starter └── 4.x ├── WebMvc → knife4j-openapi3-boot4-spring-boot-starter(React UI) ├── Spring Cloud Gateway WebFlux → knife4j-gateway-boot4-spring-boot-starter └── 非网关聚合 → knife4j-aggregation-boot4-spring-boot-starter ``` -------------------------------- ### Define Controller with Swagger 2 Annotations Source: https://knife4jnext.com/guide/getting-started Example controller using standard Swagger 2 annotations for API documentation. ```java import io.swagger.annotations.*; import org.springframework.web.bind.annotation.*; @Api(tags = "用户管理") @RestController @RequestMapping("/api/users") public class UserController { @ApiOperation("按 id 查询用户") @GetMapping("/{id}") public UserDto get(@ApiParam("用户 id") @PathVariable Long id) { return new UserDto(id, "alice"); } } ``` -------------------------------- ### Annotate Date Fields for Documentation Source: https://knife4jnext.com/guide/faq Explicitly define the schema and example format for date fields. ```java @Schema(description = "创建时间", example = "2024-01-01T00:00:00") private LocalDateTime createdAt; ``` -------------------------------- ### Verification Commands Source: https://knife4jnext.com/guide/webflux Shell commands to verify the Knife4j installation and API documentation endpoints. ```bash mvn spring-boot:run curl -I http://localhost:8080/doc.html curl http://localhost:8080/v3/api-docs | head curl http://localhost:8080/v3/api-docs/swagger-config ``` -------------------------------- ### Display Spring Security Annotations Source: https://knife4jnext.com/guide/features Example of using Spring Security annotations that Knife4j will automatically append to the interface description. ```java @RestController @RequestMapping("/api/admin") @PreAuthorize("hasAuthority('admin')") public class AdminController { @GetMapping("/users") @PreAuthorize("hasAuthority('user:list')") @Operation(summary = "管理员查看用户列表") public List listUsers() { ... } } ``` -------------------------------- ### Run OpenAPI 3 Demo Source: https://knife4jnext.com/guide/demo Commands to run the OpenAPI 3 demo project using IDE, Maven, or Docker. ```bash # 1. 打开仓库根目录,让 IDE 识别 Maven 多模块 # 2. 运行 com.baizhukui.knife4j.demo.openapi3.DemoApplication # 3. 浏览器打开 http://localhost:8080/doc.html ``` ```bash cd knife4j ./mvnw -pl knife4j-demo-openapi3 -am spring-boot:run # 浏览器打开 http://localhost:8080/doc.html ``` ```bash cd knife4j ./mvnw -pl knife4j-demo-openapi3 -am package -DskipTests java -jar knife4j-demo-openapi3/target/knife4j-demo-openapi3-*.jar ``` ```bash docker run --rm -p 8080:8080 \ ghcr.io/songxychn/knife4j-next/knife4j-next-demo-openapi3:latest ``` -------------------------------- ### Run OpenAPI 2 Demo Source: https://knife4jnext.com/guide/demo Commands to run the OpenAPI 2 demo project using IDE, Maven, or Docker. ```bash # 1. 打开仓库根目录,让 IDE 识别 Maven 多模块 # 2. 运行 com.baizhukui.knife4j.demo.openapi2.DemoApplication # 3. 浏览器打开 http://localhost:8081/doc.html ``` ```bash cd knife4j ./mvnw -pl knife4j-demo-openapi2 -am spring-boot:run # 浏览器打开 http://localhost:8081/doc.html ``` ```bash cd knife4j ./mvnw -pl knife4j-demo-openapi2 -am package -DskipTests java -jar knife4j-demo-openapi2/target/knife4j-demo-openapi2-*.jar ``` ```bash docker run --rm -p 8081:8081 \ ghcr.io/songxychn/knife4j-next/knife4j-next-demo-openapi2:latest ``` -------------------------------- ### Verify Dependency Migration Source: https://knife4jnext.com/guide/migration Check for legacy dependencies and verify the application startup and API documentation endpoints. ```bash mvn dependency:tree -Dincludes=com.baizhukui:knife4j-*,com.github.xiaoymin:knife4j-* ``` ```bash mvn spring-boot:run & curl -I http://localhost:8080/doc.html curl http://localhost:8080/v3/api-docs | head ``` ```bash curl -I http://localhost:8080/doc.html # 403 即正确 ``` -------------------------------- ### 生产环境 Nginx Basic 认证 Source: https://knife4jnext.com/guide/deployment 为文档页面添加 Basic 认证保护。 ```nginx location /doc.html { auth_basic "Knife4j Documentation"; auth_basic_user_file /etc/nginx/.htpasswd; root /opt/knife4j-static; } ``` -------------------------------- ### Define Schema for OpenAPI 3 Source: https://knife4jnext.com/guide/faq Use the @Schema annotation for field descriptions and examples when migrating from Springfox to OpenAPI 3. ```java public class UserCreateRequest { @Schema(description = "用户名", example = "alice") private String name; @Schema(description = "年龄", example = "18") private Integer age; } ``` -------------------------------- ### Verify Migration Source: https://knife4jnext.com/guide/springfox-migration Commands to verify dependency cleanup and service availability. ```bash # 1. 确认依赖 mvn dependency:tree -Dincludes=com.baizhukui:knife4j-*,io.springfox:*,org.springdoc:* # 确认没有 springfox 残留,只有 springdoc-openapi # 2. 启动验证 mvn spring-boot:run & # 3. 检查 OpenAPI3 端点 curl http://localhost:8080/v3/api-docs | head # 4. 浏览器访问 open http://localhost:8080/doc.html ``` -------------------------------- ### 确认项目依赖版本 Source: https://knife4jnext.com/reference/version-ref 使用 Maven 命令查看项目中包含的 Knife4j Next、Springdoc 及 Commons Lang3 依赖树,以排查版本冲突或安全漏洞。 ```bash mvn dependency:tree -Dincludes=com.baizhukui mvn dependency:tree -Dincludes=org.springdoc mvn dependency:tree -Dincludes=org.apache.commons:commons-lang3 ``` -------------------------------- ### Spring Boot 4.x / Spring Cloud Gateway 5.x 依赖配置 Source: https://knife4jnext.com/guide/gateway 针对 Spring Cloud Gateway 5 使用新的 WebFlux starter 坐标。 ```xml org.springframework.cloud spring-cloud-starter-gateway-server-webflux com.baizhukui knife4j-gateway-boot4-spring-boot-starter 5.2.2 ``` -------------------------------- ### 提取前端静态文件 Source: https://knife4jnext.com/guide/deployment 从 Maven 仓库的 jar 包中解压 Knife4j 前端资源到指定目录。 ```bash # 在 Maven 仓库中找到 knife4j-openapi3-ui 的 jar # 解压 META-INF/resources/ 目录 mkdir -p /opt/knife4j-static unzip -j ~/.m2/repository/com/baizhukui/knife4j-openapi3-ui/5.2.2/knife4j-openapi3-ui-5.2.2.jar \ "META-INF/resources/*" -d /opt/knife4j-static/ ``` -------------------------------- ### Spring Boot 3.x / Spring Cloud Gateway 4.x (WebFlux) 依赖配置 Source: https://knife4jnext.com/guide/gateway 在 Gateway 主工程的 pom.xml 中添加 WebFlux 相关的 starter 依赖。 ```xml org.springframework.cloud spring-cloud-starter-gateway com.baizhukui knife4j-gateway-spring-boot-starter 5.2.2 ``` -------------------------------- ### Production Environment Configuration Source: https://knife4jnext.com/reference/configuration Enables production mode with basic authentication and secure error responses. ```yaml knife4j: enable: true production: true basic: enable: true username: admin password: ${DOC_PASSWORD} ``` -------------------------------- ### 排查 OpenAPI 资源状态 Source: https://knife4jnext.com/guide/faq 使用 curl 命令检查 OpenAPI 文档及配置资源是否可正常访问。 ```bash curl -I http://localhost:8080/v3/api-docs curl -I http://localhost:8080/v3/api-docs/swagger-config ``` -------------------------------- ### Configure CSP headers Source: https://knife4jnext.com/guide/faq Required Content-Security-Policy directives to prevent UI white-screen issues. ```text default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; ``` -------------------------------- ### Minimal Knife4x Go integration Source: https://knife4jnext.com/knife4x Initialize a new Knife4x handler by providing an OpenAPI 3 JSON specification URL and the base HTTP handler. ```go package main import ( "log" "net/http" knife4x "github.com/songxychn/knife4j-next/knife4x/go" ) func main() { app := http.NewServeMux() app.HandleFunc("/openapi.json", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{ "openapi":"3.0.3", "info":{"title":"Example API","version":"1.0.0"}, "paths":{} }`)) }) handler, err := knife4x.NewHandler(knife4x.Config{ SpecURL: "/openapi.json", }, app) if err != nil { log.Fatal(err) } log.Fatal(http.ListenAndServe(":8080", handler)) } ``` -------------------------------- ### 诊断参数缺失问题 Source: https://knife4jnext.com/guide/faq 通过检查 OpenAPI 文档内容或字节码属性,确认是否因缺少 -parameters 编译参数导致参数名丢失。 ```bash # 1. 看 OpenAPI 文档 curl -s http://localhost:8080/v3/api-docs | jq '.paths."/your/path/{id}".get.parameters' # 输出 [] 就是这个问题 # 2. 看 class 字节码 javap -v target/classes/com/your/YourController.class | grep MethodParameters # 没有任何输出就是没开 -parameters ``` -------------------------------- ### Configure Custom Home Page Source: https://knife4jnext.com/guide/features Enable and set the path for a custom Markdown-based home page in the Knife4j UI. ```yaml knife4j: enable: true setting: enable-home-custom: true home-custom-path: classpath:markdown/home.md ``` -------------------------------- ### Enable Knife4j Configuration Source: https://knife4jnext.com/ Minimal YAML configuration to enable Knife4j in your application. ```yaml knife4j: enable: true ``` -------------------------------- ### Configure application.yml Source: https://knife4jnext.com/guide/getting-started Enable Knife4j and optionally configure Springdoc scanning paths and UI sorting. ```yaml knife4j: enable: true ``` ```yaml springdoc: packages-to-scan: com.example.demo paths-to-match: /api/** swagger-ui: tags-sorter: alpha operations-sorter: alpha ``` -------------------------------- ### Enable Basic authentication Source: https://knife4jnext.com/guide/faq Configure username and password to restrict access to the documentation interface. ```yaml knife4j: basic: enable: true username: admin password: ${DOC_PASSWORD} ``` -------------------------------- ### 生产环境 Nginx 拦截配置 Source: https://knife4jnext.com/guide/deployment 在生产环境中通过 Nginx 拦截文档访问。 ```nginx # 生产环境直接返回 403 location /doc.html { return 403; } location /v3/api-docs { return 403; } ``` -------------------------------- ### Run Smoke Tests Source: https://knife4jnext.com/reference/compatibility Execute the full suite of smoke tests for the project. ```bash ./tools/test-java.sh ``` -------------------------------- ### Spring Boot 3.5 / Spring Cloud Gateway Server Web MVC 依赖配置 Source: https://knife4jnext.com/guide/gateway 针对使用 Servlet 技术栈的 Server Web MVC 模式添加依赖。 ```xml org.springframework.cloud spring-cloud-starter-gateway-server-webmvc com.baizhukui knife4j-gateway-webmvc-spring-boot-starter 5.2.2 ``` -------------------------------- ### Configure DISCOVER Strategy for Web MVC Source: https://knife4jnext.com/guide/gateway Enables automatic documentation discovery for Spring Cloud Gateway Web MVC by mapping routes to OpenAPI 3 endpoints. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: user-service uri: lb://user-service predicates: - Path=/users/** knife4j: gateway: enabled: true strategy: DISCOVER discover: version: OpenAPI3 oas3: url: /v3/api-docs ``` -------------------------------- ### Add Maven Dependency Source: https://knife4jnext.com/guide/getting-started Include the knife4j-openapi3-jakarta-spring-boot-starter dependency in your pom.xml file. ```xml com.baizhukui knife4j-openapi3-jakarta-spring-boot-starter 5.2.2 ``` -------------------------------- ### 配置默认语言 Source: https://knife4jnext.com/guide/features 通过 YAML 配置文件设置 Knife4j UI 的默认显示语言。 ```yaml knife4j: enable: true setting: language: zh-CN # 也可使用 en-US 或 ja-JP ``` -------------------------------- ### Configure Aggregation Settings Source: https://knife4jnext.com/guide/aggregation Basic YAML configuration to enable aggregation and set up optional Basic Authentication. ```yaml knife4j: enable-aggregation: true # 开启聚合总开关 basic-auth: # 可选:保护聚合 UI 的 Basic 认证 enable: true username: admin password: ${KNIFE4J_AGGREGATION_PASSWORD:change-me} ``` -------------------------------- ### Configure application.yml for OpenAPI3 Source: https://knife4jnext.com/guide/getting-started Minimal configuration for Springdoc and Knife4j settings in a Spring Boot 4.x application. ```yaml 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.demo knife4j: enable: true setting: language: zh_cn ``` -------------------------------- ### Configure Custom Footer Source: https://knife4jnext.com/guide/features Enable and define custom content for the footer using Markdown. ```yaml knife4j: enable: true setting: enable-footer: true # 显示默认 Footer enable-footer-custom: true # 启用自定义 Footer 文案 footer-custom-content: Apache License 2.0 | Copyright 2019-[Knife4j](https://github.com/songxychn/knife4j-next) ``` -------------------------------- ### 生产环境内网访问限制 Source: https://knife4jnext.com/guide/deployment 通过 Nginx 限制仅允许特定网段访问文档。 ```nginx location /doc.html { allow 10.0.0.0/8; allow 172.16.0.0/12; deny all; root /opt/knife4j-static; } ``` -------------------------------- ### 使用 @EnableKnife4j 启用增强 Source: https://knife4jnext.com/reference/annotations 在 Spring Boot 启动类或配置类上启用 Knife4j 增强功能。 ```java @EnableKnife4j @SpringBootApplication public class MyApplication { ... } ``` -------------------------------- ### 静态 JSON 模式 Nginx 配置 Source: https://knife4jnext.com/guide/deployment 配置 Nginx 托管静态 JSON 文件。 ```nginx server { listen 80; server_name doc.example.com; root /opt/knife4j-static; index doc.html; location / { try_files $uri $uri/ /doc.html; } } ``` -------------------------------- ### Configure OpenAPI 3 with Spring Boot 3.x Source: https://knife4jnext.com/reference/annotations Recommended annotation combination for OpenAPI 3 and Spring Boot 3.x using Knife4j enhancements. ```java @Tag(name = "用户管理") // 控制器分组 @ApiSupport(order = 1, author = "张三") // Knife4j 增强:排序 + 作者 @RestController public class UserController { @Operation(summary = "创建用户") // 接口说明 @ApiOperationSupport(order = 1) // Knife4j 增强:排序 @PostMapping public UserVO create( @RequestBody // 请求体 @Schema(description = "创建用户请求") UserCreateRequest req ) { ... } @Operation(summary = "查询用户") // 接口说明 @GetMapping("/{id}") public UserVO get( @Parameter(description = "用户ID", example = "1") // 路径参数 @PathVariable Long id ) { ... } } ``` -------------------------------- ### Configure MANUAL Strategy for Gateway Source: https://knife4jnext.com/guide/gateway Defines specific downstream services for documentation aggregation when service discovery is not used or partial aggregation is required. ```yaml server: port: 8080 spring: cloud: gateway: routes: - id: user-service uri: http://user-service:9001 predicates: - Path=/user-service/** filters: - StripPrefix=1 knife4j: gateway: enabled: true strategy: MANUAL routes: - name: 用户中心 service-name: user-service url: /user-service/v3/api-docs context-path: /user-service order: 1 - name: 订单中心 service-name: order-service url: /order-service/v3/api-docs context-path: /order-service order: 2 ``` -------------------------------- ### Configure Maven Dependencies for Spring Boot Source: https://knife4jnext.com/ Use the appropriate starter artifact based on your Spring Boot version to integrate Knife4j Next. ```xml com.baizhukui knife4j-openapi3-boot4-spring-boot-starter 5.2.2 ``` ```xml com.baizhukui knife4j-openapi3-jakarta-spring-boot-starter 5.2.2 ``` -------------------------------- ### 服务发现 (DISCOVER) 策略配置示例 Source: https://knife4jnext.com/guide/gateway 适用于 WebFlux Gateway 的服务发现配置,通过 yaml 定义聚合规则、排除服务及服务配置覆盖。 ```yaml server: port: 8080 spring: application: name: gateway-service cloud: gateway: discovery: locator: enabled: true # Gateway 自动从注册中心生成路由 lower-case-service-id: true knife4j: gateway: enabled: true strategy: DISCOVER tags-sorter: alpha # tag 排序,可选 alpha / order operations-sorter: alpha # 接口排序,可选 alpha / method / order discover: enabled: true version: OpenAPI3 # 或 Swagger2 excluded-services: # 排除掉这些服务名(支持正则,v4.3.0+) - gateway-service - .*-config oas3: url: /v3/api-docs swagger2: url: /v2/api-docs service-config: # 针对个别服务打覆盖 user-service: group-name: 用户中心 order: 1 group-names: # 该服务在 springdoc.group-configs 里定义了多个 group - users - roles ``` -------------------------------- ### 保持不变的 YAML 配置 Source: https://knife4jnext.com/guide/migration 迁移后,YAML 配置文件中的 knife4j 相关键值无需更改。 ```yaml # 配置键不变 knife4j: enable: true production: false setting: language: zh_cn basic: enable: true username: admin password: secret ``` -------------------------------- ### Enable Interface Version Control Source: https://knife4jnext.com/guide/features Enable tracking of interface changes to display 'new' or 'modified' markers in the UI. ```yaml knife4j: enable: true setting: enable-version: true # 启用版本控制,默认 false ``` -------------------------------- ### Add OpenAPI 3 Dependency Source: https://knife4jnext.com/guide/getting-started Include the knife4j-openapi3-spring-boot-starter dependency for Spring Boot 2.x projects using springdoc-openapi. ```xml com.baizhukui knife4j-openapi3-spring-boot-starter 5.2.2 ``` -------------------------------- ### Configure OpenAPI Metadata Source: https://knife4jnext.com/reference/configuration Use the standard springdoc/OpenAPI approach to define document title, version, and description. ```java @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("用户中心接口文档") .version("1.0.0") .description("用户中心 OpenAPI 文档")); } ``` -------------------------------- ### Nginx 多服务聚合配置 Source: https://knife4jnext.com/guide/deployment 通过 Nginx 反向代理多个后端服务的 OpenAPI 接口。 ```nginx server { listen 80; server_name doc.example.com; location / { root /opt/knife4j-static; index doc.html; } # 用户服务 location /user-service/v3/api-docs { proxy_pass http://user-service:8081/v3/api-docs; } # 订单服务 location /order-service/v3/api-docs { proxy_pass http://order-service:8082/v3/api-docs; } } ``` -------------------------------- ### Configure File Upload Controller Source: https://knife4jnext.com/guide/faq Use the @RequestPart annotation with MultipartFile to enable file upload support in OpenAPI3. ```java @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public void upload(@RequestPart("file") MultipartFile file) { ... } ``` -------------------------------- ### 配置 Maven 编译参数 Source: https://knife4jnext.com/guide/faq 在 maven-compiler-plugin 中开启 parameters 选项,以保留方法参数名。 ```xml org.apache.maven.plugins maven-compiler-plugin true ``` -------------------------------- ### Configure OpenAPI 2 application.yml Source: https://knife4jnext.com/guide/getting-started Minimal configuration for OpenAPI 2, including metadata and API grouping rules. ```yaml knife4j: enable: true openapi: title: Knife4j 示例 description: "`我是测试`" email: you@example.com concat: maintainer version: v1.0 license: Apache 2.0 group: default: group-name: 默认分组 api-rule: package api-rule-resources: - com.example.demo ``` -------------------------------- ### Add OpenAPI 2 Dependency Source: https://knife4jnext.com/guide/getting-started Include the knife4j-openapi2-spring-boot-starter dependency for projects requiring Springfox compatibility. ```xml com.baizhukui knife4j-openapi2-spring-boot-starter 5.2.2 ``` -------------------------------- ### Configure Gateway Routes in YAML Source: https://knife4jnext.com/reference/configuration Define manual routes for the gateway using the knife4j.gateway.routes configuration block. ```yaml knife4j: gateway: enabled: true routes: - name: 用户服务 serviceName: user-service url: /v3/api-docs contextPath: / order: 1 ``` -------------------------------- ### 配置 Springdoc 扫描路径 Source: https://knife4jnext.com/guide/faq 通过 YAML 配置指定 Springdoc 需要扫描的 Controller 包路径,确保接口被正确识别。 ```yaml springdoc: group-configs: - group: default paths-to-match: /** packages-to-scan: com.your.project ``` -------------------------------- ### Enable Basic Authentication for Aggregation UI Source: https://knife4jnext.com/guide/aggregation Protect the aggregation UI with basic authentication using environment variables for the password. ```yaml knife4j: basic-auth: enable: true username: admin password: ${KNIFE4J_AGGREGATION_PASSWORD:change-me} ``` -------------------------------- ### Enable Docket Extension for OpenAPI 2 Source: https://knife4jnext.com/guide/getting-started Optional configuration to integrate the Docket extension system for advanced API grouping and customization. ```java @Configuration @EnableSwagger2WebMvc public class SwaggerConfig { private final OpenApiExtensionResolver openApiExtensionResolver; @Autowired public SwaggerConfig(OpenApiExtensionResolver openApiExtensionResolver) { this.openApiExtensionResolver = openApiExtensionResolver; } @Bean public Docket defaultApi() { String group = "默认分组"; return new Docket(DocumentationType.SWAGGER_2) .groupName(group) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build() .extensions(openApiExtensionResolver.buildExtensions(group)); } } ``` -------------------------------- ### 使用 @ApiSupport 控制器增强 Source: https://knife4jnext.com/reference/annotations 在 Controller 类上使用 @ApiSupport 进行排序和作者标注。 ```java @Tag(name = "用户管理") @ApiSupport(order = 1, author = "张三") @RestController public class UserController { ... } ``` -------------------------------- ### Rollback Dependency Configuration Source: https://knife4jnext.com/guide/migration Revert to the previous version of the Knife4j starter if necessary. ```xml com.github.xiaoymin knife4j-openapi3-jakarta-spring-boot-starter 4.5.0 ``` -------------------------------- ### Verify Gateway Aggregation Source: https://knife4jnext.com/guide/gateway Commands to verify downstream service documentation availability, gateway aggregation, and the configuration endpoint. ```bash # 1. 启动下游 user-service,验证 /v3/api-docs 返回 JSON curl http://user-service:9001/v3/api-docs | head # 2. 启动 gateway # 3. 确认 gateway 能拉到下游文档(DISCOVER 模式路径就是 /v3/api-docs) curl http://gateway:8080/v3/api-docs # 4. 浏览器打开 gateway doc.html open http://gateway:8080/doc.html # 5. 手动触发聚合接口(Knife4j 用来发现服务的自定义接口) curl http://gateway:8080/v3/api-docs/swagger-config ``` -------------------------------- ### Migrate Controller Annotations to OpenAPI 3 Source: https://knife4jnext.com/guide/springfox-migration Comparison of controller class and method annotations before and after migration. ```java @Api(tags = "用户管理") @RestController @RequestMapping("/api/users") public class UserController { @ApiOperation(value = "根据ID查询用户") @GetMapping("/{id}") public UserVO getById( @ApiParam(value = "用户ID", required = true) @PathVariable Long id) { return userService.getById(id); } @ApiOperation(value = "创建用户") @PostMapping public UserVO create(@RequestBody UserCreateDTO dto) { return userService.create(dto); } } ``` ```java @Tag(name = "用户管理") @RestController @RequestMapping("/api/users") public class UserController { @Operation(summary = "根据ID查询用户") @GetMapping("/{id}") public UserVO getById( @Parameter(description = "用户ID", required = true) @PathVariable Long id) { return userService.getById(id); } @Operation(summary = "创建用户") @PostMapping public UserVO create(@RequestBody UserCreateDTO dto) { return userService.create(dto); } } ``` -------------------------------- ### Spring Boot 3.x Jakarta 依赖替换 Source: https://knife4jnext.com/guide/migration 将 Spring Boot 3.x Jakarta 环境下的依赖 groupId 从 com.github.xiaoymin 更改为 com.baizhukui。 ```xml com.github.xiaoymin knife4j-openapi3-jakarta-spring-boot-starter 4.5.0 ``` ```xml com.baizhukui knife4j-openapi3-jakarta-spring-boot-starter 5.2.2 ``` -------------------------------- ### 配置 Nginx 反向代理 Source: https://knife4jnext.com/guide/deployment 配置 Nginx 托管静态文件并反向代理后端 API 接口。 ```nginx server { listen 80; server_name doc.example.com; # 静态文件 location / { root /opt/knife4j-static; index doc.html; try_files $uri $uri/ /doc.html; } # 代理 OpenAPI 接口 location /v3/api-docs { proxy_pass http://backend:8080; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # 代理旧版 Swagger2 接口(如需要) location /v2/api-docs { proxy_pass http://backend:8080; proxy_set_header Host $host; } # 代理 springdoc 分组接口 location /swagger-resources { proxy_pass http://backend:8080; } } ``` -------------------------------- ### Combine @Tag and @ApiSupport Source: https://knife4jnext.com/reference/annotations Demonstrates how to use standard OpenAPI 3 @Tag with Knife4j's @ApiSupport for grouping and metadata. ```java @Tag(name = "用户管理", description = "用户 CRUD 接口") // 标准属性 @ApiSupport(order = 1, author = "张三") // Knife4j 增强 ``` -------------------------------- ### Spring Boot 2.x + springdoc-openapi 依赖替换 Source: https://knife4jnext.com/guide/migration 将 Spring Boot 2.x 环境下的 springdoc-openapi 依赖 groupId 进行迁移。 ```xml com.github.xiaoymin knife4j-openapi3-spring-boot-starter 4.5.0 ``` ```xml com.baizhukui knife4j-openapi3-spring-boot-starter 5.2.2 ``` -------------------------------- ### Configure Cloud Aggregation Source: https://knife4jnext.com/guide/aggregation Acts as an HTTP client to periodically fetch OpenAPI documentation from downstream services. ```yaml knife4j: enable-aggregation: true cloud: enable: true routes: - name: 用户服务 uri: http://user-service:9001 location: /v3/api-docs swagger-version: "3.0" service-name: user-service order: 1 - name: 订单服务 uri: http://order-service:9002 location: /v2/api-docs swagger-version: "2.0" order: 2 route-auth: # 下游 doc.html 被 Basic 保护时 enable: true username: admin password: secret ``` -------------------------------- ### 使用 ignoreParameters 和 includeParameters Source: https://knife4jnext.com/reference/annotations 通过参数过滤控制接口文档中显示的字段。 ```java // 忽略实体类中的 id 字段 @ApiOperationSupport(ignoreParameters = {"id"}) // 忽略嵌套属性 @ApiOperationSupport(ignoreParameters = {"req.id", "req.inner.name"}) // 仅包含指定字段(与 ignoreParameters 对立) @ApiOperationSupport(includeParameters = {"name", "email"}) ``` -------------------------------- ### Configure Swagger 2 / Springfox for legacy projects Source: https://knife4jnext.com/reference/annotations Annotation usage for older projects using Swagger 2 and Springfox. ```java @Api(tags = "用户管理") // Swagger 2 分组 @ApiSort(1) // 已废弃,建议迁移 @RestController public class UserController { @ApiOperation(value = "创建用户") // Swagger 2 接口说明 @PostMapping public UserVO create(@RequestBody UserCreateRequest req) { ... } } ```