스프링 프레임워크에서 Resource는 파일, URL, 클래스패스 등의 다양한 리소스를 추상화하는 인터페이스이다.
일반적으로 애플리케이션에서 외부 파일, 설정 파일, XML, 프로퍼티 파일, 정적 리소스(CSS, JS, 이미지 등)를 다룰 때 사용된다.
스프링은 org.springframwork.core.io.Resource 인터페이스를 제공하며, 이를 통해 다양한 리소스 유형을 손쉽게 다룰 수 있다.
스프링은 다양한 리소스 유형을 지원하며, 주로 아래와 같은 Resource 구현체를 제공한다.
| 구현체 | 설명 | 예제 |
|---|---|---|
ClassPathResource | 클래스패스에 위치한 리소스를 로드할 때 사용 | new ClassPathResource("config/app.properties") |
FileSystemResource | 파일 시스템에 있는 리소스를 로드할 때 사용 | new FileSystemResource("C:/config/app.properties") |
UrlResource | URL(HTTP, FTP 등)을 통해 리소스를 로드할 때 사용 | new UrlResource("https://example.com/file.txt") |
ServletContextResource | 웹 애플리케이션의 WEB-INF 폴더 내 리소스를 로드 | new ServletContextResource(servletContext, "/WEB-INF/config.xml") |
@Value를 이용한 리소스 주입스프링에서는 @Value 어노테이션을 이용해 간단하게 리소스를 주입할 수 있다.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
@Component
public class ResourceExample {
@Value("classpath:config/app.properties") // 클래스패스에서 파일 로드
private Resource resource;
public void printResourceDetails() {
try {
System.out.println("파일 이름: " + resource.getFilename());
System.out.println("파일 경로: " + resource.getURI());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ResourceLoader를 이용한 리소스 로딩스프링에서는 ResourceLoader를 사용해 동적으로 리소스를 로드할 수 있다.
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
@Service
public class ResourceLoaderExample {
private final ResourceLoader resourceLoader;
public ResourceLoaderExample(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void loadResource() {
Resource resource = resourceLoader.getResource("classpath:config/app.properties");
System.out.println("파일 존재 여부: " + resource.exists());
}
}
resourceLoader.getResource("classpath:..."): 클래스패스에서 파일 로드resourceLoader.getResource("file:..."): 파일 시스템에서 로드resourceLoader.getResource("http://..."): URL에서 리소스 로드ApplicationContext를 이용한 리소스 로딩스프링의 ApplicationContext는 자체적으로 ResourceLoader 기능을 제공한다.
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;
public class ApplicationContextExample {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Resource resource = context.getResource("classpath:config/app.properties");
System.out.println("파일 존재 여부: " + resource.exists());
}
}
Resource는 파일, URL, 클래스패스 리소스를 다룰 수 있도록 추상화된 인터페이스Resource의 주요 구현체: ClassPathResource, FileSystemResource, UrlResource, ServletContextResource 등@Value("classpath:...")를 사용한 주입ResourceLoader를 통한 동적 로딩ApplicationContext를 통한 로딩스프링의 Resource를 활용하면 다양한 리소스를 손쉽게 관리할 수 있어, 설정 파일이나 정적 파일을 다룰 때 유용하다.