springboot3.4 集成knife4j
时间: 2025-05-30 16:29:23 浏览: 22
### Spring Boot 3.4 中集成 Knife4j 的配置教程
#### 1. 添加依赖
在 `pom.xml` 文件中引入 Knife4j 的依赖。对于 JDK 17 和 Spring Boot 3.4.0 版本,推荐使用以下依赖:
```xml
<dependency>
<groupId>com.github.xingfudeshi</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.6.0</version>
</dependency>
```
此依赖解决了 Spring Boot 升级至 3.4 后可能出现的兼容性问题[^2]。
---
#### 2. 配置应用属性
在 `application.yml` 或 `application.properties` 文件中添加 Knife4j 的基础配置。以下是 YAML 格式的示例配置:
```yaml
server:
port: 8080
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
knife4j:
enable: true
swagger-ui:
enabled: true
api-docs:
enabled: true
```
上述配置启用了 Knife4j 并允许通过浏览器访问其 UI 页面[^1]。
---
#### 3. 创建 Swagger 文档配置类
创建一个 Java 类用于初始化和配置 Swagger 文档的相关参数。例如:
```java
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableKnife4j
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.paths(PathSelectors.any()) // 可选:指定路径过滤器
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot 3 + Knife4j API文档") // 设置标题
.description("API接口描述") // 描述
.version("1.0.0") // 版本号
.build();
}
}
```
以上代码片段定义了一个基于 OpenAPI 3.0 的 RESTful 接口文档,并集成了 Knife4j 增强功能。
---
#### 4. 访问 Knife4j 页面
完成上述配置后,启动应用程序并打开浏览器访问以下地址查看 Knife4j 提供的增强版 Swagger UI 页面:
```
http://localhost:8080/doc.html
```
如果遇到无法加载页面的情况,请尝试按照引用中的建议,使用 Postman 或其他 HTTP 工具请求 `/v3/api-docs/default` 路径,并确保请求头携带必要的认证信息[^3]。
---
#### 注意事项
- 如果仍然出现 `Handler dispatch failed: java.lang.NoSuchMethodError` 错误,请确认所使用的依赖版本是否匹配当前 Spring Boot 和 Jakarta EE 的标准。
- 确保项目的 Maven 构建工具已成功下载所需依赖项。
---
### 示例总结
通过上述步骤可以顺利实现 Spring Boot 3.4 与 Knife4j 的集成。最终效果是一个支持 OpenAPI 3.0 规范的强大 API 文档展示平台。
阅读全文
相关推荐


















