본문 바로가기
Spring/Spring Core

[Section 1] IoC 컨테이너 9부: ResourceLoader

by kevinntech 2020. 9. 6.

해당 게시물은 백기선님의 스프링 프레임워크 핵심 기술 강좌를 정리한 내용 입니다.

 

 

ResourceLoader

 

- ResourceLoader는 리소스를 읽어오는 기능을 제공하는 인터페이스이다.

 

1) resources 폴더에 test.txt 파일을 생성 한다.

 

2) ResourceLoarder 객체를 얻은 다음에 주요 메서드 호출

    ResourceLoader의 getResource() : 지정한 리소스의 Resource 객체를 얻는다.
    Resource의 exists()                              : 리소스가 존재하는지 확인한다.        
              ""          getDescription()            : 전체 경로를 포함한 파일 이름 또는 실제 URL      


    ResourceLoader 빈을 주입 받은 다음, Resource 객체를 얻고 해당 객체의 주요 메서드 결과를 출력 한다. 

 

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    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(Files.readString(Path.of(resource.getURI())));  // 파일 내용을 읽어서 출력 (Java 11 버전 기능)
    }
}

 

3) 프로젝트 빌드 

     프로젝트를 빌드하면 resources 디렉토리의 파일들은 target/classes로 복사 된다.

     target/classes는 classpath의 root이며  getResource()를 호출할 때 "classpath:"를 지정 하였으므로 
     target/classes를 기준으로 리소스를 찾는다.

댓글