【问题标题】:How do I locate resource files in a Spring Boot project deployed to Elastic Beanstalk?如何在部署到 Elastic Beanstalk 的 Spring Boot 项目中找到资源文件?
【发布时间】:2020-01-06 19:38:11
【问题描述】:

我的 Spring Boot 项目在 src/main/resources 文件夹中包含一个 XML 文件,这是此类文件的常用位置。

在本地和 Pivotal CloudFoundary 上运行,我能够找到文件并将其读入,但在 Beanstalk 上,该过程会导致一个空文件。

定位和读取文件的代码:

URL url = getClass().getResource("/myFile.xml");
LOG.info("File location: " + url.toString());

生成的日志条目:

File location: jar:file:/var/app/current/application.jar!/WEB-INF/classes!/myFile.xml

当我通过 SSH 连接到 EC2 实例时,我可以在指定目录中找到该 jar。

我是否需要配置 Maven 才能将此文件移动到某处?

更新

我已经意识到我需要像在 InputStream 中一样对待这个文件,因为它被打包在 jar 中。

我现在使用以下代码,导致以下错误:

FileUtils.copyInputStreamToFile(new ClassPathResource("myFile.xml").getInputStream(), myFile);

java.lang.NullPointerException: null
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:345) ~[commons-io-2.5.jar:2.5]

FileUtils.copyInputStreamToFile(new ClassPathResource("classpath:myFile.xml").getInputStream(), myFile);


java.io.FileNotFoundException: class path resource [classpath:myFile.xml] cannot be opened because it does not exist

谢谢!

【问题讨论】:

    标签: spring amazon-web-services spring-boot amazon-ec2 amazon-elastic-beanstalk


    【解决方案1】:

    你的 pom.xml 是什么样子的?也许有一个资源过滤器处于活动状态? 在 Spring 应用程序中,您可以使用 File file = ResourceUtils.getFile("classpath:myFile.xml"); 来读取资源文件。

    你能用ResourceUtils检查结果吗?

    这里是 api 文档的链接: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html#getFile-java.lang.String-

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-10
      • 2017-04-12
      • 2021-06-02
      • 1970-01-01
      • 2018-04-26
      • 2020-07-05
      • 2020-02-25
      • 2015-09-07
      相关资源
      最近更新 更多