백기선(인프런 강의)/스프링 프레임워크 핵심 기술

IoC 컨테이너와 빈(5) - ResourceLoader

레알윙 2020. 3. 22. 18:16
반응형

text.txt 파일 위치

@Controller
public class HomeController {
	@Autowired
	ResourceLoader resourceloader;
    //ApplicationContext resourceLoader; // 이것도 가능

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) throws Exception {
		Resource resource = resourceloader.getResource("classpath:test.txt");
		System.out.println(resource.exists());
		System.out.println(resource.getFile()); // 파일 객체
		System.out.println(resource.getFilename()); // 파일 이름
		System.out.println(resource.getInputStream()); // InputStream 객체
		System.out.println(resource.getURL()); // URL 객체
		System.out.println(resource.getURI()); // URI 객체

		System.out.println("======================================================");

		Path path = Paths.get(resource.getURI());
		List<String> content = Files.readAllLines(path);

		for (String text : content) {
			System.out.println(text);
		}

		return "home";
	}
}

 

 

 

true
C:\spring\worksapce\test\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\study\WEB-INF\classes\test.txt
test.txt
java.io.ByteArrayInputStream@39a2fb8
file:/C:/spring/worksapce/test/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/study/WEB-INF/classes/test.txt
file:/C:/spring/worksapce/test/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/study/WEB-INF/classes/test.txt
======================================================
hello spring

 

ApplicationContext resourceLoader로 구현해도 가능하다. 그 이유는 ApplicationContext가 ResourceLoader를 구현했기 때문이다. 

 

반응형