Spring Ch 2. 추상화 - ResourceLoader와 Resource 추상화


Resource 추상화

  • java는 java.net.URL이라는 URL 클래스로 리소스에 접근할 수 있다.
  • classPath 또는 ServletContext 기준 상대경로의 리소스(low-level Resource)에 접근하려면 핸들러를 등록하여 URL접미사를 만들어 사용해야 한다. 이는 코드만으로 리소스의 출처를 확인하기 불편하며 비효율적이고 불편하다.
  • Spring의 Resource 객체는 URL 클래스를 추상화하여 low-level 리소스에 접근할 수 있도록 기능을 제공하고 있다.
1
2
3
4
5
6
7
8
public interface Resource extends InputStreamSource {
boolean exists();//리소스가 존재하는지 확인하는 함수.
URL getURL() throws IOException;//URL 주소를 얻는 함수.
File getFile() throws IOException;//파일을 얻는 함수.
Resource createRelative(String relativePath) throws IOException; //상대경로를 설정한다.
String getFilename();//파일 명을 얻는 함수.
String getDescription();//리소스의 타입을 리턴하는 함수.
}

리소스 타입

  • Resource 인터페이스를 구현한 구현체들은 다음과 같다.
    1. UrlResource - http:, https:, ftp:, file:, jar:과 같이 URL로 접근할 수 있는 리소스에 사용한다.
    2. ClassPathResource - classPath:로 접근할 수 있는 리소스에 사용한다.
    3. FileSystemResource - 파일 시스템으로 접근할 수 있는 리소스에 사용한다.
    4. ServletContextResource - Web Application의 경로 내에서 상대 경로로 접근할 수 있는 리소스에 사용한다.
  • 각 구현체들은 ApplicationContext의 타입에 따라 맞는 리소스 구현체를 소유할 수 있다.

    1. ApplicationContext - ApplicationContext의 기본형. Url 리소스를 얻을 수 있다.
    2. ClassPathXmlApplicationContext - classPath 리소스를 얻을 수 있다.
    3. FileSystemXmlApplicationContext - 파일 시스템 리소스를 얻을 수 있다.
    4. WebApplicationContext - Web Application 리소스를 얻을 수 있다.
  • ApplicaitonContext는 java.URL의 접두어로 다른 리소스에 접근할 수 있다. ex) classpath:test.txt

ResourceLoader

  • ResourceLoader는 경로로부터 리소스를 가져오는 역할을 수행한다.
  • getResource 함수 하나만으로 다양한 리소스 타입의 Resource 객체를 얻을 수 있으므로 매우 효율적이다.
1
2
3
4
5
6
7
8
9
10
@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())));
}
  • ApplicationContext는 ResourceLoader를 상속받기 때문에 ApplicationContext 객체만으로도 같은 기능을 수행할 수 있다.
1
2
3
4
5
6
7
8
9
10
@Autowired
ApplicationContext appCtx;

@Override
public void run(ApplicationArguments args) throws Exception{
Resource resource = appCtx.getResource("classpath:test.txt");
System.out.println(resource.exists());
System.out.println(resource.getDescription());
System.out.println(Files.readString(Path.of(resource.getURI())));
}

댓글