while(1) work();
Spring Core 핥아먹기
핥다[할따]
물, 불, 빛, 시선 따위가 물체의 표면을 부드럽게 스치거나 비추거나 머무르다.


Spring 6 릴리즈를 기념해, Spring 공식 문서를 읽으며 정리한 시리즈입니다.
Spring Core와 Spring Context에 대해 살펴봅니다.
반응형

1. Spring의 Resource 인터페이스

Java의 표준 java.net.URL의 클래스는 기능이 부족하다.

  • classpath로부터 파일을 읽어올 수 없음
  • ServletContext로 부터의 상대경로로 파일을 읽어올 수 없음
  • 특수 접두사에 대해 핸들러 등록이 복잡함

Spring은 Resource 인터페이스(org.springframework.core.io.Resource)를 만들어 여러 resource들을 추상화했다.

Resource 인터페이스는 아래와 같다.

<code />
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(); }

Resource 인터페이스를 구현한 구현 클래스는 아래와 같다.

  • UrlResource
  • ClassPathResource
  • FileSystemResource
  • PathResource
  • ServletContextResource
  • InputStreamResource
  • ByteArrayResource

2. Resource 사용 예시

<code />
@Value("classpath:data.txt") Resource dataResource;

@Value 어노테이션을 통해 Resource를 주입받을 수 있다.

<code />
try { Resource resource = context.getResource("classpath:application.properties"); File file = resource.getFile(); String data = new String(Files.readAllBytes(file.toPath())); System.out.println(data); } catch (IOException e) { System.out.println("Something wrong.."); }

ApplicationContext(의 상위 인터페이스인 ResourceLoader)의 getResource를 통해 Resource를 가져올 수 있다.

3. PS

여기까지가 Spring framework document - core의 1장 내용이다.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans

반응형

'핥아먹기 시리즈 > Spring Core 핥아먹기' 카테고리의 다른 글

14. 스프링 표현언어(SpEL)  (0) 2022.12.28
13. Null Safety  (0) 2022.12.28
11. 기타 기능들  (0) 2022.12.28
10. Component Scan과 생성자 주입  (0) 2022.12.28
9. 의존관계 자동 주입 (@Autowired)  (0) 2022.12.28
profile

while(1) work();

@유호건

❤️댓글은 언제나 힘이 됩니다❤️ 궁금한 점이나 잘못된 내용이 있다면 댓글로 남겨주세요.

검색 태그