如何在部署到 Elastic Beanstalk 的 Spring Boot 项目中查找资源文件?



我的 Spring 引导项目在 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

谢谢!

你的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-

最新更新