본문 바로가기
Spring Boot/Core

Resource 추상화

by Holy Moly 2022. 7. 25.

특징

  • java.net.URL을 추상화 한 갓
  • 스프링 내부에서 많이 사용하는 인터페이스

 

추상화 한 이유

  • 클래스 패스 기준 리소스 읽어오는 기능 부재
  • ServletContext를 기준으로 상대 경로로 읽어오는 기능 부재
  • 새로운 핸들러를 등록하여 특별한 URL 접미사를 만들어 사용 가능 하지만 구현 복잡 및 편의성 부족

 

주요 메소드

  • 상속 받은 인터페이스
  • getInputStream()
  • exists()
  • isOpen()
  • getDescription()

 

구현체

  • UrlResource : 기본 지원 프로토콜 http,https,file.jar등
  • ClassPathResource : 지원 접두어 classpath
  • FileSystemResource 
  • ServletContextResource : 웹 어플리케이션 루트에서 상대 경로 리소스를 찾는다.
  • ...

 

리소스 읽어오기

  • Resource의 타입은 location문자열과 ApplicationContext의 타입에 따라 결정
    • ClassPathXmlApplicationContext -> ClassPathResource
    • FileSystemXmlApplicationContext -> FileSystemResource
    • WebApplicationContext -> ServletContextResource
  • ApplicationContext의 타입과 상관없이 리소스 타입을 강제하려면 URL + prefix이용
    • classpath:me/hol22mol22/config.xml -> ClassPathResource
    • file:///me.~~~ -> FileSystemResource
    • 스프링부트는 서블릿 기반 WebApplicationContext를 사용하기 때문에, 이외의 타입 필요시 접두어를 이용하는 방법 추천(명시적인 방법)

 

// 접두어 사용시 ClassPathResource
Resource resource = resourceLoader.getResource("classpath:test.txt");
System.out.println(resourceLoader.getClass());
System.out.println(resource.getClass());

// 접두어 미사용시 ServletContextResource
resource = resourceLoader.getResource("test.txt");
System.out.println(resource.getClass());

다음과 같이 기본적인 resouceLoader는 WebServerApplicationContext를 이용

classpath 접두어 사용시 리소스는 ClassPathResource인 것을 확인

접두어 미 사용시 ServletContextResource사용

'Spring Boot > Core' 카테고리의 다른 글

스프링 AOP  (0) 2022.08.01
SpEL  (0) 2022.07.30
데이터 바인딩 추상화  (0) 2022.07.26
Validation 추상화  (0) 2022.07.25
IoC 컨테이너와 빈  (0) 2022.07.19

댓글