如何在 Spring Boot 中访问 src/main/resources/文件夹中的资源文件 [英] How to access a resource file in src/main/resources/ folder in Spring Boot

查看:59
本文介绍了如何在 Spring Boot 中访问 src/main/resources/文件夹中的资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 src/main/resources/XYZ/view 文件夹中的 xsd,其中 XYZ/view 文件夹是由我创建的,文件夹中有 abc.xsd,我需要用它来进行 xml 验证.

I'm trying to access xsd in src/main/resources/XYZ/view folder where XYZ/view folder are created by me and folder has abc.xsd which I need for xml validation.

当我每次得到空结果都尝试访问 xsd 时,

When I try to access the xsd every time I get the result as null,

我试过了,

1)

@Value(value = "classpath:XYZ/view/abc.xsd")
private static Resource dataStructureXSD;
InputStream is = dataStructureXSD.getInputStream();
Source schemaSource = new StreamSource(is);
Schema schema = factory.newSchema(schemaSource);

2)

Resource resource = new ClassPathResource("abc.xsd");
File file = resource.getFile();

以及我为获取资源或类加载器等而制作的更多路径

and many more trails I made to get the resource or classloader etc.

最后我得到了 xsd,

Finally I get the xsd with,

File file = new File(new ClassPathResource("/src/main/resources/XYZ/view/abc.xsd").getPath());Schema schema = factory.newSchema(file);

File file = new File(new ClassPathResource("/src/main/resources/XYZ/view/abc.xsd").getPath()); Schema schema = factory.newSchema(file);

它正在工作,我想知道为什么其他两条路径会出错,或者为什么它对我不起作用而对其他人很好.:(

and it is working, I want to know why the other two trails would have gone wrong or why it didn't work for me and fine for others. :(

或者还有其他我遗漏的好方法

Or is there other good way of doing it which I'm missing

推荐答案

@Value 注释 用于将属性值注入变量,通常是字符串或简单的原始值.您可以找到更多信息 此处.

如果要加载资源文件,请使用 ResourceLoader 如:

If you want to load a resource file, use a ResourceLoader like:

@Autowired
private ResourceLoader resourceLoader;

...

final Resource fileResource = resourceLoader.getResource("classpath:XYZ/view/abc.xsd");

然后您可以通过以下方式访问资源:

Then you can access the resource with:

fileResource.getInputStream()fileResource.getFile()

这篇关于如何在 Spring Boot 中访问 src/main/resources/文件夹中的资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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