Spring Boot 访问静态资源缺少 scr/main/resources [英] Spring Boot access static resources missing scr/main/resources
问题描述
我正在开发一个 Spring Boot 应用程序.我需要在开始时解析一个 XML 文件 (countries.xml).问题是我不知道把它放在哪里以便我可以访问它.我的文件夹结构是
I am working on a Spring Boot application. I need to parse an XML file (countries.xml) on start. The problem is that I do not understand where to put it so that I could access it. My folders structure is
ProjectDirectory/src/main/java
ProjectDirectory/src/main/resources/countries.xml
我的第一个想法是将它放在 src/main/resources 中,但是当我尝试创建文件 (countries.xml) 时,我得到了一个 NPE 并且堆栈跟踪显示我的文件在 ProjectDirectory 中查看(因此 src/main/resources/未添加).我尝试创建文件 (resources/countries.xml),路径看起来像 ProjectDirectory/resources/countries.xml(所以再次没有添加 src/main).
My first idea was to put it in src/main/resources, but when I try to create File (countries.xml) I get a NPE and the stacktrace shows that my file is looked in the ProjectDirectory (so src/main/resources/ is not added). I tried to create File (resources/countries.xml) and the path would look like ProjectDirectory/resources/countries.xml (so again src/main is not added).
我尝试添加它但没有结果
I tried adding this with no result
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
super.addResourceHandlers(registry);
}
我知道我可以手动添加 src/main/,但我想了解为什么它不能正常工作.我还尝试了 ResourceLoader 的示例 - 没有结果.
I know that I can add src/main/ manually, but I want to understand why is it not working as it has to. I also tried examples with ResourceLoader - with the same no result.
有人能提出问题是什么吗?
Could anyone suggest what the problem is?
更新:仅供日后参考 - 构建项目后,我遇到了访问文件的问题,因此我将 File 更改为 InputStream
UPDATE: Just for future references - after building the project, I encountered problem with accessing file, so I changed File to InputStream
InputStream is = new ClassPathResource("countries.xml").getInputStream();
推荐答案
只需使用 Spring 类型 ClassPathResource.
Just use Spring type ClassPathResource.
File file = new ClassPathResource("countries.xml").getFile();
只要这个文件在类路径上,Spring 就会找到它.在开发和测试期间,这可以是 src/main/resources
.在生产中,它可以是当前运行目录.
As long as this file is somewhere on classpath Spring will find it. This can be src/main/resources
during development and testing. In production, it can be current running directory.
如果文件在胖 JAR 中,这种方法不起作用.在这种情况下,您需要使用:
This approach doesn't work if file is in fat JAR. In such case you need to use:
InputStream is = new ClassPathResource("countries.xml").getInputStream();
这篇关于Spring Boot 访问静态资源缺少 scr/main/resources的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!