Spring Boot 3整合Swagger 3
问题描述
在使用Spring Boot 3时,开发者尝试集成Springfox Swagger 3(通过添加springfox-boot-starter
依赖),但在访问Swagger页面(如/swagger-ui.html
)时遇到404错误(Whitelabel错误页)。问题的核心在于:
- 依赖不兼容:Springfox Swagger 3(如版本3.0.0)不支持Spring Boot 3的特性(特别是Jakarta EE 9+)。
- 访问路径错误:即使使用了正确依赖,开发者也可能访问了错误的URL路径,或存在安全配置问题。
- 缓存问题:IDE(如IntelliJ)缓存可能导致旧依赖残留,使配置变更不生效。
解决方案
1. 替换为Springdoc OpenAPI
Spring Boot 3官方推荐使用springdoc-openapi
替代Springfox,这是唯一兼容Spring Boot 3的Swagger解决方案。
添加Maven依赖
xml
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 使用最新版本 -->
</dependency>
添加Gradle依赖
groovy
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
TIP
最新版本可查看Springdoc官网,避免使用低于2.0.0
的版本。
2. 访问Swagger页面
集成后,访问以下URL:
- API文档(JSON格式):
http://localhost:8080/v3/api-docs
- Swagger UI界面:
http://localhost:8080/swagger-ui/index.html
WARNING
某些旧版本路径/swagger-ui.html
会被重定向到/swagger-ui/index.html
,但直接访问后者更可靠。
3. 自定义路径配置
在application.properties
中调整路径:
properties
# 修改API文档路径
springdoc.api-docs.path=/api-docs
# 修改Swagger UI路径
springdoc.swagger-ui.path=/custom-swagger
访问URL将变为:http://localhost:8080/custom-swagger/index.html
4. Spring Security集成配置
若项目启用了Spring Security,需允许Swagger路径访问:
java
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger-ui.html"
).permitAll() // 允许所有用户访问
.anyRequest().authenticated()
)
.csrf(csrf -> csrf.disable()); // 可选:禁用CSRF保护
return http.build();
}
5. 高级配置示例
自定义API信息和身份验证设置:
java
@Configuration
@OpenAPIDefinition(
info = @Info(title = "API文档", version = "1.0", description = "系统接口文档"),
security = @SecurityRequirement(name = "JWT")
)
@SecurityScheme(
name = "JWT",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "JWT"
)
public class OpenApiConfig {
}
常见问题解决
1. IDE缓存导致的404错误
在IntelliJ中按以下步骤清理缓存:
- 点击菜单 File > Invalidate Caches...
- 选择 Invalidate and Restart
- 重新构建项目:
mvn clean install -DskipTests
2. 依赖冲突问题
移除所有springfox
相关依赖,确保不存在以下内容:
xml
<!-- 需删除此依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
3. 路径访问错误
检查:
- 项目是否有自定义context-path(如
server.servlet.context-path=/api
),则Swagger路径应为http://localhost:8080/api/swagger-ui/index.html
- 检查端口是否被覆盖(
server.port=8081
)
最佳实践总结
- 始终使用springdoc:Springfox在Spring Boot 3中已过时
- 保持版本最新:通过Springdoc版本列表确认
- 生产环境禁用:通过配置关闭Swaggerproperties
springdoc.api-docs.enabled=false springdoc.swagger-ui.enabled=false
- 细化扫描范围(可选):properties
springdoc.packages-to-scan=com.example.controller
完成以上步骤后,即可在Spring Boot 3中正常使用Swagger 3进行API文档管理和测试。