Spring Boot无法访问前端打包dist静态资源 求助排查问题
问题分析与解决
核心问题
- 资源路径映射不匹配:index.html中静态资源使用相对路径
./static/xxx,但配置的资源处理器仅匹配/dist/**,导致请求/static/xxx时Spring Boot无法定位到资源。 - WebMvcConfigurationSupport覆盖默认配置:继承该类会禁用Spring Boot自动配置的资源处理规则,需手动补充完整映射逻辑。
具体修复步骤
1. 调整application.yml配置
更新静态资源位置,确保dist目录下的资源能被识别:
spring: web: resources: static-locations: "classpath:/dist/, classpath:/static/"
2. 修改SpringWebMvcConfig配置类
替换继承WebMvcConfigurationSupport为实现WebMvcConfigurer接口,修正资源映射规则并添加默认路由:
@Configuration public class SpringWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 映射/static/**到dist下的static目录 registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/dist/static/"); // 映射根路径下的图片、svg文件到dist根目录 registry.addResourceHandler("/*.png", "/*.svg") .addResourceLocations("classpath:/dist/"); } @Override public void addViewControllers(ViewControllerRegistry registry) { // 根路径直接跳转index.html registry.addViewController("/").setViewName("forward:/index.html"); } }
说明:实现
WebMvcConfigurer不会覆盖Spring Boot默认资源配置,避免额外冲突。
3. 确认文件结构
确保资源存放路径正确:
src/main/resources/ └── dist/ ├── index.html ├── pwa-192x192.png ├── safari-pinned-tab.svg └── static/ ├── js/ │ └── index-d3549438.js └── css/ └── index-db70e0a5.css
4. 重启应用
完成修改后重启Spring Boot,访问http://localhost:8080/或http://localhost:8080/index.html,静态资源即可正常加载。
内容的提问来源于stack exchange,提问作者real_rourou
相关产品推荐
相关产品推荐

