Java/Spring framework

Spring framework core (7) - ResourceLoader

감동이중요해 2020. 1. 14. 01:09

IoC Container - ResourceLoader

Application에 포함한 리소스를 불러오는 기능을 제공하는 인터페이스이다.

기본적으로 ResourceLoader를 주입받아 사용할 수 있으나,

ApplicationContext로도 같은 기능을 사용할 수 있다.

ApplicationContextResourceLoader를 상속받아 구현했기 때문이다.

ResourceLoader

AppRunner를 작성하여 활용법을 알아본다.

Spring boot 프로젝트를 생성하고 아래의 소스코드를 작성한다.

  1. AppRunner
@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Resource resource1 = resourceLoader.getResource("classpath:/test.txt");
        Resource resource2 = resourceLoader.getResource("classpath:/application.properties");
        System.out.println(resource1.exists());
        System.out.println(resource2.exists());
    }
}

결과

false
true

classpath 아래에 test.txt가 없으니 false,

spring boot 프로젝트를 생성하면 application.properties가 같이 생성되기 때문에 true가 나왔다.

ClassPath

여기서 classpath는 앱이 실행된 후 실제로 리소스가 저장되는 위치를 말한다.

별도의 설정을 하지 않았다면 프로젝트 내부에 target이라는 폴더가 생성되는데 target/classes를 찾아보면 작성한 소스 코드가 이 위치에 전부 있을 것이다.

src/main/java, src/main/resource 등 기본으로 등록되는 classpath가 여러 개 존재한다.

 

작성한 소스 코드 전체는 아래 링크에서 확인할 수 있다.

https://github.com/dhmin5693/Spring-core-study/tree/master/ResourceLoader