Spring Boot 3.4.1升级后Swagger UI 404:无法加载openapi.yaml静态资源
问题分析与解决方案
1. Spring Boot 3.4.1静态资源服务的变更
是的,Spring Boot 3.4.x版本收紧了默认静态资源的路径匹配规则。之前版本中src/main/resources/下的自定义子目录可能被间接映射,但3.4.x默认仅暴露以下四个目录的静态资源:
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
你的openapi/目录不在默认列表中,因此无法直接通过/openapi/api-v1.0.yaml访问到文件。
2. 新版本是否需要额外配置?
需要。要么将文件迁移到默认静态资源目录,要么手动配置Spring Boot使其识别openapi/目录作为静态资源路径。
3. 修复方案
提供两种可行修复方式,任选其一即可:
方案一:调整文件路径(最简单)
将src/main/resources/openapi/目录移动到src/main/resources/static/openapi/。Spring Boot会自动映射该目录,/openapi/api-v1.0.yaml可直接访问,无需修改其他配置。
方案二:添加静态资源映射配置
如果不想移动文件,可通过配置让Spring Boot识别openapi/目录:
方式A:Java配置类
创建WebMvc配置类,手动注册资源处理器:
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 OpenApiResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/openapi/**") .addResourceLocations("classpath:/openapi/"); } }
方式B:配置文件(application.yml)
在配置文件中扩展静态资源位置:
spring: web: resources: static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/openapi/
验证步骤
- 重新构建并启动应用
- 直接访问
http://localhost:8080/openapi/api-v1.0.yaml,确认能正常返回YAML文件内容 - 打开Swagger UI,即可正常加载API定义
内容的提问来源于stack exchange,提问作者Heri.R
相关产品推荐
相关产品推荐

