Vaadin 24项目打包JAR后无法读取src/main/resources静态资源
解决Vaadin 24打包JAR后静态资源InputStream为null的问题
核心问题:类加载器选择错误
你使用的ClassLoader.getSystemResourceAsStream("/myimg.png")依赖系统类加载器,但Spring Boot打包的可执行JAR(BOOT-INF/classes结构)中,系统类加载器无法直接访问BOOT-INF内部的资源,这就是开发模式正常、生产JAR失效的根本原因。
修复方案
1. 改用当前类的类加载器加载资源
替换原有代码为:
InputStream is = getClass().getClassLoader().getResourceAsStream("myimg.png"); if (is == null) { throw new RuntimeException("未找到资源myimg.png"); } return is.readAllBytes();
注意:不要加前缀斜杠/,类加载器的getResourceAsStream默认从类路径根目录开始查找,而你的资源已经处于类路径根(BOOT-INF/classes等价于类路径根)。
2. 更可靠的Spring资源加载方式(推荐)
如果项目是Spring Boot整合Vaadin,直接使用Spring的ResourceLoader或Resource接口加载,规避类加载器的兼容性问题:
import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import java.io.IOException; import java.nio.file.Files; @Component public class ResourceLoaderService { private final ResourceLoader resourceLoader; public ResourceLoaderService(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public byte[] loadImage() throws IOException { Resource resource = resourceLoader.getResource("classpath:myimg.png"); return Files.readAllBytes(resource.getFile().toPath()); } }
3. Vaadin专属资源配置(可选)
如果是要在Vaadin组件中展示静态资源,推荐将资源放在src/main/resources/META-INF/resources/vaadin/目录下,Vaadin会自动处理资源访问路径:
- 资源存放路径:
src/main/resources/META-INF/resources/vaadin/myimg.png - Vaadin组件中直接引用:
new Image("myimg.png", "自定义图片"),无需手动读取InputStream。
验证步骤
- 打包JAR后,执行
jar tf your-app.jar命令,确认BOOT-INF/classes/myimg.png存在 - 运行JAR时,确保没有自定义类加载器配置干扰资源加载
内容的提问来源于stack exchange,提问作者padmalcom
相关产品推荐
相关产品推荐

