如何在 Spring Boot 中访问 src/main/resources/ 文件夹中的资源文件

新手上路,请多包涵

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

当我每次得到结果为 null 时尝试访问 xsd 时,

我试过,

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();

以及我为获取资源或类加载器等所做的更多尝试。

最后我得到了 xsd,

文件 file = new File(new ClassPathResource(“/src/main/resources/XYZ/view/abc.xsd”).getPath());模式模式 = factory.newSchema(file);

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

或者还有其他我想念的好方法吗

原文由 tyro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 753
2 个回答

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

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

 @Autowired
private ResourceLoader resourceLoader;

...

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

然后你可以访问资源:

fileResource.getInputStream()fileResource.getFile()

原文由 Kevin Peters 发布,翻译遵循 CC BY-SA 3.0 许可协议

@ValueResourceLoader 都适合我。我在 src/main/resources/ 中有一个简单的文本文件,我能够用这两种方法阅读它。

也许 static 关键字是罪魁祸首?

 package com.zetcode;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements CommandLineRunner {

    @Value("classpath:thermopylae.txt")
    private Resource res;

    //@Autowired
    //private ResourceLoader resourceLoader;

    @Override
    public void run(String... args) throws Exception {

       // Resource fileResource = resourceLoader.getResource("classpath:thermopylae.txt");

        List<String> lines = Files.readAllLines(Paths.get(res.getURI()),
                StandardCharsets.UTF_8);

        for (String line : lines) {

            System.out.println(line);

        }
    }
}

的在 Spring Boot 中加载资源 教程中提供了完整的工作代码示例。

原文由 Jan Bodnar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题