2017-05-05 121 views
1

我试图访问src/main/resources/XYZ/view文件夹中的xsd,其中XYZ/view文件夹由我和文件夹创建abc.xsd,我需要进行xml验证。如何访问src/main/resources /文件夹中的资源文件在Spring Boot

当我想尽我得到的结果为空时,

我曾尝试为,

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

以及我为获取资源或类加载程序而创建的更多路径。

最后我得到与XSD,

档案文件=新的文件(新使用ClassPathResource( “/ src目录/主/资源/ XYZ /查看/ abc.xsd”)的getPath()); Schema schema = factory.newSchema(file);

它正在工作,我想知道为什么其他两条路径会出错或为什么它不适合我并为其他人处理。 :(

还是有它我丢失

回答

6

@Value annotation用于注入属性值到变量,通常是字符串或简单的原始值做它的其他的好办法。你可以找到更多信息here

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

@Autowired 
private ResourceLoader resourceLoader; 

... 

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

然后你就可以与访问资源

fileResource.getInputStream()fileResource.getFile()

+0

是的,它为我工作谢谢凯文 – tyro

2

我都@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教程可用。

相关问题