目录
✦ **问题 1:依赖冲突(如 spring-webmvc 版本冲突)
✦ **问题 3:Spring Boot 3.x 启动报错(如 jakarta 包冲突)
Swagger官网: https://swagger.io/
Knife4j 官网:https://doc.xiaominfo.com/docs/quick-start
一、接口文档核心认知
1. 什么是接口文档?
接口的**“契约说明书”**,明确接口的:
-
请求:URL、方法(GET/POST等)、参数(类型、是否必填、示例)、请求头/体格式。
-
响应:数据结构(正常/异常响应)、错误码、字段说明。
-
补充:接口描述、业务场景、版本变更记录。
2. 为什么选 Swagger + Knife4j?
工具 | 优势 | 不足 |
Swagger 原生 | 行业标准,自动生成文档,支持在线调试。 | 界面简陋,功能基础,中文支持弱。 |
Knife4j | 国内团队开发(增强 Swagger),界面美观、支持文档导出/排序/分组,完美适配 Spring Boot。 | 依赖 Swagger 生态,需额外学习。 |
二、Swagger 原生集成(基础版)
1. 依赖引入(分 Spring Boot 版本)
✦ Spring Boot 2.x
<!-- Swagger 核心 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI(原生界面) -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
✦ Spring Boot 3.x
Swagger 原生 **不兼容 Spring Boot 3.x**(因 Jakarta EE 包名变更),建议直接切换到 **Knife4j**(下文重点讲),或改用 springdoc-openapi
。
2. 配置类编写(SwaggerConfig.java
)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 // 启用 Swagger
@Profile({"dev", "test"}) // 仅开发/测试环境启用,生产环境关闭
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 扫描 Controller 包路径(替换为实际包名)
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
// 文档基本信息(可自定义)
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("系统接口文档")
.description("包含用户、订单等模块接口")
.contact(new Contact("作者", "https://blog.example.com", "email@example.com"))
.version("1.0")
.build();
}
}
3. 注解使用(核心!让文档更清晰)
注解 | 作用范围 | 说明 |
| Controller | 标记接口分组(如“用户模块”) |
| 方法 | 描述接口功能 |
| 方法参数 | 描述单个参数(名称、说明、是否必填) |
| 实体类 | 标记实体类 |
| 实体字段 | 描述字段含义、示例、是否必填等 |
4. 访问测试
浏览器访问:http://localhost:8080/swagger-ui.html
(默认路径,需结合项目上下文路径)。
如果在配置文件中加了前缀,比如api:http://localhost:8080/api/swagger-ui.html
5. 生产环境必关!
-
方式 1:通过
@Profile
限定环境(如上述配置,仅dev
/test
环境加载)。 -
方式 2:在
application.yml
中加开关:swagger: enabled: ${SWAGGER_ENABLE:false} # 生产环境设为 false
三、Knife4j 集成(增强版,推荐生产使用)
1. 为什么选 Knife4j?
-
界面更友好:支持接口排序、文档导出(Markdown/HTML/Word)、在线调试增强。
-
兼容 Spring Boot 3.x:专门提供
knife4j-spring-boot3-starter
。 -
中文生态:文档详细,国内团队维护,问题响应快。
2. 依赖引入(分 Spring Boot 版本)
✦ Spring Boot 2.x
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
✦ Spring Boot 3.x
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot3-starter</artifactId>
<version>4.0.0</version>
</dependency>
依赖查询:
-
Knife4j 官网:https://doc.xiaominfo.com
-
Maven 中央仓库:https://mvnrepository.com/artifact/com.github.xiaoymin
3. 配置类调整(Knife4jConfig.java
)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; // Knife4j 注解
@Configuration
@EnableSwagger2WebMvc // 替代 @EnableSwagger2
@Profile({"dev", "test"})
public class Knife4jConfig {
@Bean(value = "defaultApi")
public Docket defaultApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("系统接口文档")
.description("Knife4j 增强版文档")
.contact(new Contact("作者", "https://blog.example.com", "email@example.com"))
.version("1.0")
.build();
}
}
4. 增强功能体验
✦ 接口排序(让文档更规整)
在 Controller 类 上加 @ApiSort(1)
(数字越小,排序越靠前):
@Api(tags = "用户模块", value = "用户相关接口")
@ApiSort(1) // 排序优先级:1 > 2 > 3...
public class UserController { ... }
✦ 文档导出(一键生成接口文档)
访问 http://localhost:8080/doc.html
→ 右上角 “导出” → 选择格式(Markdown/HTML/Word)。
如有前缀(如api):http://localhost:8080/api/doc.html
✦ 分组管理(多模块拆分)
为不同模块创建独立 Docket
,实现分组:
@Bean(value = "userApi")
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("用户模块") // 分组名称
.apiInfo(userApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.user.controller"))
.build();
}
private ApiInfo userApiInfo() {
return new ApiInfoBuilder().title("用户模块接口").version("1.0").build();
}
5. 访问地址
Knife4j 默认路径:http://localhost:8080/doc.html
(界面更美观,功能更全)。
四、版本兼容与排坑指南
1. 核心版本对应关系
Spring Boot 版本 | 推荐 Knife4j 版本 | Swagger 兼容性 |
2.4.x ~ 2.7.x |
| 完美兼容 |
3.x+ |
| 原生 Swagger 不兼容,必须用增强版 |
2. 常见问题 & 解决方案
✦ **问题 1:依赖冲突(如 spring-webmvc
版本冲突)
-
现象:启动报错
ClassNotFoundException
或NoSuchMethodError
。 -
解决:
-
执行
mvn dependency:tree
分析依赖树,找到冲突的包。 -
通过
<exclusions>
排除冲突依赖:<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.9</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </exclusion> </exclusions> </dependency>
-
✦ **问题 2:访问 doc.html
报 404
-
原因:Spring Boot 静态资源未正确映射(Knife4j 需加载前端资源)。
-
解决:
-
确保依赖正确引入,且配置类加了
@EnableSwagger2WebMvc
(Knife4j 专属注解)。 -
若用 Spring Security,需放行
/doc.html
和/webjars/**
路径:@Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/doc.html", "/webjars/**", "/swagger-resources/**"); }
-
✦ **问题 3:Spring Boot 3.x 启动报错(如 jakarta
包冲突)
-
原因:Knife4j 版本不对,未使用
spring-boot3-starter
。 -
解决:替换依赖为
knife4j-spring-boot3-starter:4.0.0+
。
五、扩展功能与最佳实践
1. 全局参数配置(如 Token 自动携带)
在 Docket
中添加全局请求参数(如 Token):
.globalRequestParameters(
Collections.singletonList(
new RequestParameterBuilder()
.name("Authorization")
.description("Bearer Token")
.in(ParameterType.HEADER)
.required(true)
.build()
)
)
2. 整合 OAuth2 认证
让文档支持 Token 调试:
.securitySchemes(Collections.singletonList(
new OAuthBuilder()
.name("OAuth2")
.grantTypes(Collections.singletonList(new ImplicitGrant()))
.scopes(Collections.singletonList(new AuthorizationScope("read", "只读权限")))
.build()
))
3. 与 Postman 联动
Knife4j 支持 **直接导出 Postman 集合**:
-
访问
doc.html
→ 右上角 “导出” → 选择Postman 集合
。 -
导入 Postman,直接运行接口测试(自动携带参数)。
六、总结:Swagger vs Knife4j 怎么选?
-
纯学习/小项目:Swagger 原生足够,快速搭建。
-
生产环境/团队协作:必选 **Knife4j**,功能更全、界面更友好,兼容新框架(如 Spring Boot 3.x)。