해당 게시물은 백기선님의 스프링 프레임워크 핵심 기술 강좌를 정리한 내용 입니다.
ResourceLoader
- ResourceLoader는 리소스를 읽어오는 기능을 제공하는 인터페이스이다.
1) resources 폴더에 test.txt 파일을 생성 한다.
2) ResourceLoarder 객체를 얻은 다음에 주요 메서드 호출
ResourceLoader의 getResource() : 지정한 리소스의 Resource 객체를 얻는다.
Resource의 exists() : 리소스가 존재하는지 확인한다.
"" getDescription() : 전체 경로를 포함한 파일 이름 또는 실제 URL
ResourceLoader 빈을 주입 받은 다음, Resource 객체를 얻고 해당 객체의 주요 메서드 결과를 출력 한다.
@Component
public class AppRunner implements ApplicationRunner {
@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()))); // 파일 내용을 읽어서 출력 (Java 11 버전 기능)
}
}
3) 프로젝트 빌드
프로젝트를 빌드하면 resources 디렉토리의 파일들은 target/classes로 복사 된다.
target/classes는 classpath의 root이며 getResource()를 호출할 때 "classpath:"를 지정 하였으므로
target/classes를 기준으로 리소스를 찾는다.
'Spring > Spring Core' 카테고리의 다른 글
| [Section 2] Validation 추상화 (0) | 2020.09.13 |
|---|---|
| [Section 2] Resource 추상화 (0) | 2020.09.13 |
| [Section 1] IoC 컨테이너 8부: ApplicationEventPublisher (0) | 2020.09.06 |
| [Section 1] IoC 컨테이너 7부: MessageSource (0) | 2020.09.06 |
| [Section 1] IoC 컨테이너 6부: Environment 2부. 프로퍼티 (0) | 2020.09.03 |
댓글