ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ResourceLoader 관련 정리
    SPRING 2020. 4. 19. 20:43

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

    ApplicationContext가 ResourceLoader를 상속받은 상태이기 때문에 ApplicationContext를 통해서 ResourceLoader 기능을 사용하는 것이 가능하다.

     

    ApplicationRunner에서 아래와 같이 실행을 하면 resource의 존재여부,  루트등을 출력할 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        @Autowired
        ResourceLoader resourceLoader;
        
        @Override
        public void run(ApplicationArguments args) throws Exception {
            // TODO Auto-generated method stub
            
            Resource resource = resourceLoader.getResource("classpath:test.txt");
            System.out.println(resource.exists());
            System.out.println(resource.getDescription());
            System.out.println(resource.getURI().getPath());
     
        }
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

     

    출력 :

    true
    class path resource [test.txt]
    /C:/dev/git/springbootStudy/demo1/target/classes/test.txt

     

    test.txt 위치 : 

     

    Resource 추상화

    특징 

    - JAVA.net.URL을 추상화 한것이다.

    - 스프링 내부에서 많이 사용하는 클래스이다.

     

    주요 메소드 

    - getInputStream

    - exist()  

    - isOpen()

    - getDescription() : 전체 경로를 포함한 파일 이름 또는 실제 URL

     

    구현체 목록

     

    1. UrlResource : URL을 기준으로 리소스를 읽어들임. 기본적으로 지원하는 프로토콜 http, https, ftp, file, jar

    2. ClassPathResource : 지원하는 접두어가 classpath:  클래스패스를 기준으로 리소스를 읽어들임.

    3. FileSystemResource : 파일 시스템을 기준으로 리소스를 읽어들임,

    4. ServletContextResource : 웹 어플리케이션 루트에서 상대 경로로 리소스를 찾는다.

     

    Resource 타입은 location 문자열과 ApplicationContext 타입에 따라 결정된다.

     

    - ClassPathXmlApplicationContext => ClassPathResource

    - FileSystemXmlApplicationContext => FileSystemResource

    - WebApplicationContext => ServletContextResource

     

     

Designed by Tistory.