2017-05-05 69 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教程可用。

相關問題