본문 바로가기

Develop/Spring

Spring Resource

728x90

모든 시스템은 다양한 자원들이 필요합니다.

순수 자바에서는 Stream을 통해 파일을 접근하며 외부 파일 접근 등이 모두 어렵습니다.

스프링에서는 외부 sftp, http, 파일 등에서 자원들을 쉽게 끌어올 수 있도록 Resource를 제공합니다.

스프링에서는 Resource라는 인터페이스를 만들어서 리소스를 관리합니다.

Resource Interface

public interface Resource extends InputStreamSource {
	boolean exists();
    
	default boolean isReadable() {
		return exists();
	}
    
	default boolean isOpen() {
		return false;
	}

	default boolean isFile() {
		return false;
	}
    
	URL getURL() throws IOException;
	URI getURI() throws IOException;
	File getFile() throws IOException;
    
	default ReadableByteChannel readableChannel() throws IOException {
		return Channels.newChannel(getInputStream());
	}

	long contentLength() throws IOException;
	long lastModified() throws IOException;
	Resource createRelative(String relativePath) throws IOException;

	@Nullable
	String getFilename();
	String getDescription();

}

자바의 표준 클래스들은 다양한 리소스(URL, 파일 등)에 접근할 때 충분한 기능을 제공하지 않습니다.

스프링은 필요한 기능을 만들어서 제공합니다.

 

Resource 구현체 목록

Spring 내부의 Resource 구현체 중 대표적인 몇 가지

(바로 하위의 구현체는 아니고 몇 중으로 더 추상화 되어 있음)

UrlResource

java.net.URL을 래핑한 버전이며 다양한 종류(ftp:, file:, http: 등의 prefix로 접근 유형 판단)의

Resource에 접근이 가능하지만 기본적으로는 http(s)로 원격 접근에 사용합니다.

ClassPathResource

classpath(소스 코드를 빌드한 target/classes 폴더) 하위의 리소스 접근 시 사용합니다.

FileSystemResource

이름과 마찬가지로 File을 다루기 위한 리소스 구현체 입니다.

ServletContextResource, InputStreamResource, ByteArrayResource

Servlet 어플리케이션 루트 하위 파일, InputStream, ByteArrayInput 스트림을 가져오기 위한 구현체 입니다.


Spring ResourceLoader

스프링 프로젝트 내에서 스프링이 Resource(파일 등)에 접근할 때 사용하는 기능입니다.

public interface ResourceLoader {

    Resource getResource(String location);
    ClassLoader getClassLoader();
}
  • 기본적으로 applicationContext에 구현되어 있습니다.
  • 프로젝트내의 파일(주로 classpath 하위 파일)에 접근할 일이 있을 경우 활용합니다.
  • 대부분의 사전 정의된 파일들은 자동으로 로딩되도록 되어 있으나 추가로 필요한 파일이 있을 때 이 부분의 활용이 가능합니다.

리소스 로딩 예시

@Service
public class ResourceService {
    @Autowired
    ApplicationContext ctx;
    
    public void setResource() {
        Resource myTemplate =
            ctx.getResource("classpath:some/resource/path/myTemplate.txt");
            // ctx.getResource("file:some/resource/path/myTemplate.txt");
            // ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
        }
}

만약 `ctx.getResource("classpath:some/resource/path/myTemplate.txt");` 에서

`classpath:` 스킴이 생략되면 기본적으로 classpath 위치에서 로드하게 됩니다.


ResourcePatternResolver

이러한 스킴을 통해서 스프링이 마음대로 접근할 수 있는 이유는

단순한 리소스 로더를 구현한 것이 아니라 ResourcePatternResolver라는

스키마를 자동으로 선택해주는 기능이 들어있는 구현체를 사용해서 만든 것이기 때문입니다.

  • ResourcePatternResolver는 스프링 ApplicationContext에서 ResourceLoader를 불러올 때 사용하는 Interface입니다.
  • 위치 지정자 패턴("classpath:***", "file:***", "http:")에 따라 자동으로 해당 ResourceLoader 구현체를 선택합니다.

ApplicationContext는 ResourcePatternResolver 인터페이스를 상속받는 구조입니다.

public interface ApplicationContext extends EnvironmentCapable,
    ListableBeanFactory, HierachicalBeanFactory,
    MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
    // Spring ApplicationContext interface
}

Application Contexts & Resource Paths

applicationContext(스프링의 핵심 설정)을 이루는 설정 값을 가져오는 방법들

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

ApplicationContext ctx =
        new FileSystemXmlApplicationContext("conf/appContent.xml");
       
 ApplicationContext ctx =
         new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");

스프링이 ApplicationContext를 생성할 때 XML Configuration 파일을 로드할 때도

ResourceLoader가 사용된다는 것을 알 수 있습니다.

'Develop > Spring' 카테고리의 다른 글

(작성 중) Spring web.xml  (0) 2022.11.16
Spring SpEL  (0) 2022.11.16
Spring DataBinding  (0) 2022.11.16
Spring Validation  (0) 2022.11.16
Spring AOP  (0) 2022.11.16