You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Native无法读取/resources目录文件问题排查

Spring Boot原生镜像无法读取resources文件的解决方案
  • 修正资源匹配正则
    你在native-image.properties中配置的-H:IncludeResources=".*/*.txt$"正则无法匹配根目录下的file.txt(编译后资源位于classpath根,无层级目录)。请调整为精准匹配规则:

    Args = -H:IncludeResources="^file.txt$"
    # 若需匹配所有txt文件,可改为:
    # Args = -H:IncludeResources=".*\\.txt$"
    
  • 使用Spring Boot原生资源配置
    无需手动编辑native-image.properties,Spring Boot提供了更适配的配置方式,在application.properties中添加:

    spring.native.resources.includes=file.txt
    # 匹配所有txt文件则写:
    # spring.native.resources.includes=*.txt
    

    该配置会自动告知GraalVM原生镜像工具包含指定资源,更符合Spring生态规范。

  • 完善native-maven-plugin配置
    确保插件配置开启Spring Boot支持,避免手动配置遗漏:

    <profile>
        <id>native</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.graalvm.buildtools</groupId>
                    <artifactId>native-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>build-native</id>
                            <goals>
                                <goal>compile-no-fork</goal>
                            </goals>
                            <phase>package</phase>
                        </execution>
                    </executions>
                    <configuration>
                        <imageName>${project.artifactId}</imageName>
                        <springBoot>true</springBoot>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
    
  • 验证资源是否被包含
    构建完成后,用GraalVM工具检查原生镜像是否包含目标文件:

    native-image-inspect ./你的原生可执行文件名 | grep "file.txt"
    

    若输出包含file.txt,说明资源已被包含,需检查代码读取逻辑;若未输出,说明构建配置仍需调整。

  • 确认代码读取路径
    确保代码中传入的filename是"file.txt"(不要带开头斜杠/),因为ClassLoader.getResourceAsStream默认从classpath根目录查找,带斜杠会导致路径匹配失败。

内容的提问来源于stack exchange,提问作者ThCollignon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:08:13