【问题标题】:Spring boot Resource getFile() is not working [duplicate]Spring引导资源getFile()不起作用[重复]
【发布时间】:2020-06-17 09:52:07
【问题描述】:

在我的 Spring Boot 项目中,我试图加载位于资源文件夹中的 xml 文件。如果我尝试使用

加载文件
Resource resource= resourceLoader.getResource("classpath:" + filepath);
File tempFile = resource.getFile();

我在 docker 容器中收到以下错误,因为该文件存在于 jar 文件的 BOOT-INF\classes 文件夹中(包装类型为 jar)

Exception occur while generating mock sso response java.io.FileNotFoundException: class path resource [mock_sso_response.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/polst-webapp-2.1.5-SNAPSHOT.jar!/BOOT-INF/classes!/mock_sso_response.xml

但是使用 getInputStream 可以。

Resource resource= resourceLoader.getResource("classpath:" + MOCK_SSO_RESPONSE_FILE);
InputStream inputStream = resource.getInputStream();

如果有人能分享这背后的原因,那将是非常有帮助的,还有什么更好的/替代的方法可以在 Spring Boot 中加载 xml 文件。任何帮助将不胜感激

【问题讨论】:

  • 你在变量文件路径和 MOCK_SSO_RESPONSE_FILE 中传递了什么?只是为了双重确认它具有相同的价值。
  • 看看this question。简而言之,resource.getFile() 需要文件系统上的资源。
  • @Victor 谢谢你回答了我的问题
  • 这能回答你的问题吗? Classpath resource not found when running as jar

标签: java spring spring-boot docker


【解决方案1】:

来自春天Resource JavaDoc

抛出: FileNotFoundException - 如果资源不能被解析为绝对文件路径,即如果资源在文件系统中不可用

所以 Resource 的实现似乎不支持 getFile() 的使用。通常你想用 isFile() 检查资源是否可以通过 getFile() 解析。

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 2023-04-08
    • 2019-01-17
    • 2016-09-25
    • 2019-09-16
    • 2018-12-30
    • 1970-01-01
    • 2019-02-23
    • 2016-08-04
    相关资源
    最近更新 更多