Vaadin14+Spring Boot打包JAR后无法访问META-INF/resources静态资源如何解决
问题根因
Vaadin 14生产模式打包运行时,默认会将所有未明确匹配Spring MVC路由的请求转发给Vaadin Servlet处理,因此你放在META-INF/resources下的静态资源请求会被Vaadin的路由拦截,返回无对应路由提示。IDE中直接运行默认是开发模式,不会启用全量请求拦截,因此可以正常访问。
解决方案
方案1:配置Vaadin请求排除规则(推荐)
在application.properties(或application.yml)中添加如下配置,指定Vaadin不需要拦截的路径/后缀:
# 放行所有txt文件,可根据需求调整规则,比如/*.html、/static/*等 vaadin.exclude-urls=*.txt
如果需要放行多个规则用逗号分隔即可,示例:vaadin.exclude-urls=*.txt,*.html,/assets/*
方案2:自定义静态资源映射(方案1不生效时使用)
新增Spring MVC配置类,手动指定静态资源路径映射,优先级高于Vaadin拦截规则:
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 StaticResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/META-INF/resources/") .setCachePeriod(3600); // 调整优先级确保高于Vaadin拦截器 registry.order(Integer.MIN_VALUE); } }
验证步骤
- 保存配置后执行
mvn clean package重新打包 - 启动打包后的JAR包,访问
localhost:8080/asd.txt即可正常获取文件内容
内容的提问来源于stack exchange,提问作者markus
相关产品推荐
相关产品推荐

