How to access a resource file in src/main/resources/ folder in Spring Boot

后端 未结 3 1402
清歌不尽
清歌不尽 2021-01-03 00:43

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.

When

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 00:45

    Both @Value and ResourceLoader work OK for me. I have a simple text file in src/main/resources/ and I was able to read it with both approaches.

    Maybe the static keyword is the culprit?

    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 lines = Files.readAllLines(Paths.get(res.getURI()),
                    StandardCharsets.UTF_8);
    
            for (String line : lines) {
    
                System.out.println(line);
    
            }
        }
    }
    

    A full working code example is available in my Loading resouces in Spring Boot tutorial.

提交回复
热议问题