- spring boot resource 파일 access2023년 08월 27일
- 알쓸개잡
- 작성자
- 2023.08.27.:16
spring boot 에서 resource 디렉토리에 있는 모든 파일은 빌드 시 application root 에 복사 됩니다. 이번 포스팅에서는 spring boot 에서 resource 파일을 access 하는 3가지 방법을 소개합니다.
- ResourceLoader
- ClassPathResource 생성자
- @Value annotation
샘플 코드는 test 코드이며 test 디렉토리의 resource 에 있는 샘플 파일 경로는 아래 이미지와 같습니다.
resources 파일 ResourceLoader
Spring boot 에서 ResourceLoader 는 자동 주입됩니다. ResourceLoader를 통해서 resource 파일을 로딩 하는 경우에는 getResource() 메소드에 넘겨주는 파라미터에 prefix 를 붙여 resource 타입을 강제 할 수 있습니다.
package com.example.access.resource; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; @ExtendWith(SpringExtension.class) public class AccessResourceFileTest { @Autowired ResourceLoader resourceLoader; @Test @DisplayName("ResourceLoader 를 이용한 access 테스트") void resource_loader_test() throws IOException { //resourceLoader 를 통한 resource 파일 로딩 //classpath: 와 같은 prefix 를 붙이지 않는 경우 디폴트로 클래스패스를 기준으로 //파일을 찾아 로딩합니다. Resource resource = resourceLoader.getResource("resource_file_sample.txt"); File file = resource.getFile(); Assertions.assertThat(file.getName()).isEqualTo("resource_file_sample.txt"); System.out.println("absolute path: " + file.getAbsolutePath()); try(InputStream inputStream = resource.getInputStream()) { byte[] bytes = inputStream.readAllBytes(); System.out.println("read data: " + new String(bytes)); } resource = resourceLoader.getResource("classpath:data/sample_data_file.txt"); file = resource.getFile(); Assertions.assertThat(file.getName()).isEqualTo("sample_data_file.txt"); System.out.println("absolute path: " + file.getAbsolutePath()); try(InputStream inputStream = resource.getInputStream()) { byte[] bytes = inputStream.readAllBytes(); System.out.println("read data: " + new String(bytes)); } } }
결과는 두 테스트 코드 동일합니다.
absolute path: /access-resource/target/test-classes/resource_file_sample.txt read data: resource file sample absolute path: /access-resource/target/test-classes/data/sample_data_file.txt read data: sample data file
ClassPathResource 생성자
prefix 와 함께 파일 경로를 ClassPathResource 생성자에 전달하면 자동으로 해당 파일을 로드 합니다.
@Test @DisplayName("ClassPathResource 생성자를 이용한 access 테스트") void class_path_resource_test() throws IOException { //ClassPathResource 는 prefix 를 붙이지 않습니다. //classpath 를 기준으로 파일을 찾아 로딩합니다. Resource resource = new ClassPathResource("data/sample_data_file.txt"); File file = resource.getFile(); Assertions.assertThat(file.getName()).isEqualTo("sample_data_file.txt"); System.out.println("absolute path: " + file.getAbsolutePath()); try(InputStream inputStream = resource.getInputStream()) { byte[] bytes = inputStream.readAllBytes(); System.out.println("read data: " + new String(bytes)); } }
absolute path: /access-resource/target/test-classes/data/sample_data_file.txt read data: sample data file
@Value annotation
package com.example.access.resource; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; @ExtendWith(SpringExtension.class) public class ValueAnnotationResourceFileAccessTest { @Value("classpath:data/sample_data_file.txt") Resource sampleResource; @Test @DisplayName("@Value annotation 으로 resource access 테스트") void value_annotation_resource_access_test() throws IOException { File file = sampleResource.getFile(); Assertions.assertThat(file.getName()).isEqualTo("sample_data_file.txt"); System.out.println("absolute path: " + file.getAbsolutePath()); try(InputStream inputStream = sampleResource.getInputStream()) { byte[] bytes = inputStream.readAllBytes(); System.out.println("read data: " + new String(bytes)); } } }
absolute path: /access-resource/target/test-classes/data/sample_data_file.txt read data: sample data file
'스프링부트' 카테고리의 다른 글
Spring SSE (Server Sent Event) 사용 방법 (0) 2023.09.09 Spring Boot GraalVM Native Image 빌드 하기 (0) 2023.09.04 spring-boot-starter-parent 와 spring-boot-dependencies (0) 2023.08.15 spring boot 필드값 조건별 validation 하기 - json subtype (0) 2023.07.29 spring boot 필드값 조건별 validation 하기 - custom annotation (0) 2023.07.29 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)