Spring Ch 2. 추상화 - ResourceLoader와 Resource 추상화
Resource 추상화
- java는 java.net.URL이라는 URL 클래스로 리소스에 접근할 수 있다.
- classPath 또는 ServletContext 기준 상대경로의 리소스(low-level Resource)에 접근하려면 핸들러를 등록하여 URL접미사를 만들어 사용해야 한다. 이는 코드만으로 리소스의 출처를 확인하기 불편하며 비효율적이고 불편하다.
- Spring의 Resource 객체는 URL 클래스를 추상화하여 low-level 리소스에 접근할 수 있도록 기능을 제공하고 있다.
1 | public interface Resource extends InputStreamSource { |
리소스 타입
- Resource 인터페이스를 구현한 구현체들은 다음과 같다.
- UrlResource - http:, https:, ftp:, file:, jar:과 같이 URL로 접근할 수 있는 리소스에 사용한다.
- ClassPathResource - classPath:로 접근할 수 있는 리소스에 사용한다.
- FileSystemResource - 파일 시스템으로 접근할 수 있는 리소스에 사용한다.
- ServletContextResource - Web Application의 경로 내에서 상대 경로로 접근할 수 있는 리소스에 사용한다.
각 구현체들은 ApplicationContext의 타입에 따라 맞는 리소스 구현체를 소유할 수 있다.
- ApplicationContext - ApplicationContext의 기본형. Url 리소스를 얻을 수 있다.
- ClassPathXmlApplicationContext - classPath 리소스를 얻을 수 있다.
- FileSystemXmlApplicationContext - 파일 시스템 리소스를 얻을 수 있다.
- WebApplicationContext - Web Application 리소스를 얻을 수 있다.
ApplicaitonContext는 java.URL의 접두어로 다른 리소스에 접근할 수 있다. ex) classpath:test.txt
ResourceLoader
- ResourceLoader는 경로로부터 리소스를 가져오는 역할을 수행한다.
- getResource 함수 하나만으로 다양한 리소스 타입의 Resource 객체를 얻을 수 있으므로 매우 효율적이다.
1 |
|
- ApplicationContext는 ResourceLoader를 상속받기 때문에 ApplicationContext 객체만으로도 같은 기능을 수행할 수 있다.
1 |
|