首页 文章

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

提问于
浏览
3

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

当我每次将结果作为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 file = new File(new ClassPathResource(“/ src / main / resources / XYZ / view / abc.xsd”) . getPath()); Schema schema = factory.newSchema(file);

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

还是有其他好方法可以做到这一点,我很遗憾

2 回答

  • 2

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

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

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

    然后您可以使用以下命令访问资源:

    fileResource.getInputStream()fileResource.getFile()

  • 8

    @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);
    
            }
        }
    }
    

    我的Loading resouces in Spring Boot教程中提供了完整的工作代码示例 .

相关问题