Spring Boot访问静态资源缺少SCR/主/资源 [英] Spring Boot access static resources missing scr/main/resources

查看:183
本文介绍了Spring Boot访问静态资源缺少SCR/主/资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发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中,但是当我尝试创建File(countries.xml)时,我得到一个NPE,并且stacktrace显示我的文件在ProjectDirectory中查找(所以src/main/resources/未添加).我尝试创建File(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类型

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/主/资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆