2020-4-1 다시 시작하는 스프링(6) - 리소스로7

ResourceLoader

  • 리소스를 로드를 해준다.
public interface ResourceLoader {
    String CLASSPATH_URL_PREFIX = "classpath:";

    Resource getResource(String var1);

    @Nullable
    ClassLoader getClassLoader();
}
@Component
public class AppRunner implements ApplicationRunner {
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Resource resource = resourceLoader.getResource("classpath:test.txt");
        System.out.println(resource.exists());
        System.out.println(resource.getDescription());
        System.out.println(resource.contentLength());
        System.out.println(resource.getFilename());
        System.out.println(resource.getURI());
    }
}

//result
true
class path resource [test.txt]
11
test.txt
file:/Users/jaeyeonkim/Desktop/spring-inflearn/target/classes/test.txt
  • classpath:text.txt를 설정했는데, target디렉토리의 하위 디렉토리인 classes에 resources디렉토리에 있는 파일들이 빌드될때 추가된다. 여기서 로드를 한다.
Written on April 1, 2020