-
Spring Boot [02.Spring Resource와 SpEL]JAVA/Spring 2022. 1. 18. 20:14
1. Spring Resource
java.net.URL의 한계(classpath 내부 접근이나 상대경로 등)를 넘어서기 위해 스프링에서 추가로 구현됨
업무에서 많이 사용되는 부분이 아닐수도 있으나, 스프링의 내부 동작을 이해하기 위해서 필요한 부분
Resource Interface와 그 구현체들
public interface Resource extends InputStreamSource { boolean exists(); boolean isReadable(); boolean isOpen(); boolean isFile(); URL getURL() throws IOException; URI getURI() throws IOException; File getFile() throws IOException; ReadableBytechannel readableChannel() throws IOException; long contentLength() throws IOException; long lastModfied() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFileName(); String getDescription(); }
Resource 구현체 목록
다음은 Spring 내부 Resource 구현체 중 대표적인 몇가지이다.
UrlResource
java.net.URL을 래핑한 버젼, 다양한 종류(ftp:, file:, http:, 등의 prefix로 접근유형 판단)의 Resource에 접근 가능하지만 기본적으로는 http(s)로 원격 접근
classPathResource
classpath(소스코드를 빌드한 결과(기본적으로 target/classes 폴더)) 하위의 리소스 접근 시 사용
FileSystemResource
이름과 같이 File을 다루기 위한 리소스 구현체
ServletContextResource, InputStreamResource, ByteArrayResource
Servlet 어플리케이션 루트 하위 파일, InputStream, ByteArrayInput 스트림을 가져오기 위한 구현체
Spring ResourceLoader
스프링 프로젝트 내 Resource(파일 등)에 접근할 때 사용하는 기능
- 기본적으로 applicationContext에서 구현이 되어 있음
- 프로젝트 내 파일(주로 classpath 하위 파일)에 접근할 일이 있을 경우 활용
- 대부분의 사전정의된 파일들은 자동으로 로딩되도록 되어 있으나, 추가로 필요한 파일이 있을 때 이 부분을 활용
@Service public class ResourceService { @Autowired ApplicationContext ctx; public void setResource() { Resource myTemplate = ctx.getResource("classpath:some/resource/path/myTemplate.txt"); // ctx.getResource("file:/some/resource/path/myTemplate.txt"); // ctx.getResource("http://myhost.com/resource/path/myTemplate.txt"); } }
ResourcePatternResolver
스프링 ApplicationContext에서 ResourceLoader를 불러올 때 사용하는 Interface
위치 지정자 패턴("classpath:***", "file:***", "http:")에 따라 자동으로 Resource 로더 구현체를 선택
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchialBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver { // Spring ApplicationContext interface }
Application Contexts & Resource Paths
applicationContext(스프링의 핵심설정)을 이루는 설정값을 가져오는 방법들
// let's create an applicationContext ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml"); ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml"); ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml"); // then you can use ctx as a Spring Bear bear = (Bear) ctx.getBean("bear");
2. SpEL (Spring Expression Language)
Expression Language는 짧고 간단한 문법을 통해 필요한 데이터나 설정 값을 얻어올 수 있게 하는 특별한 형태의 표현식에 가까운 간편한 언어이다. (그래프 접근 등이 가능)
SpEL은 그 중에서도 스프링 모든 영역에서 사용 가능한 언어 형식이다.
- 주로 @Value("$(config.value)")와 같은 방식으로 설정값을 주입받는 데 사용
SpEL의 값 평가 (Evaluation)
- SpELParser는 ""안에 들어있는 문자열을 평가(evaluation)해서 결과값을 만들어낸다.
- "Hello World"는 문자열 리터럴이 되며, concat이라는 메서드도 호출할 수 있다.
- String 객체를 new로 생성해서 사용도 가능
ExpressionParser parser = new SpelExpressionParser(); Expression exp = praser.parseExpression("'Hello World'"); String message = (String) exp.getValue(); // "Hello World" Expression expWow = parser.parseExpression("'Hello World.'.concat('!')"); String messageWow = (String) expWow.getValue(); // "Hello World!" Expression expString = parser.parseExpression("new String('hello world').toUpperCase()"); String messageString = expString.getValue(String.class); // "HELLO WORLD"
Bean의 Property를 설정할 때 사용하는 방식
- 기본적으로 #{ <expression string> } 방식으로 property를 설정
- application.properties (또는 application.yml)의 값을 가져올 때는 ${ <property.name> } 방식으로 가져옴
- 환경에 따라 다른 동작을 하게끔 하고싶을 때 주로 사용!
@Component public class SimpleComponent { @Value("#{ 1+1 }") int two; // 2 @Value("#{ 2 eq 2 }") boolean isTrue; // true @Value("${ server.hostname }") String hostName; // www.server.com @Value("#{ ${ server.hostname } eq 'www.server.com'}") boolean isHostSame; // true }
'JAVA > Spring' 카테고리의 다른 글
Spring Boot [01. About Spring Boot] (0) 2022.01.06 패스트캠퍼스 챌린지 19일차 (0) 2021.11.19 패스트캠퍼스 챌린지 18일차 (0) 2021.11.18 패스트캠퍼스 챌린지 17일차 (0) 2021.11.17 패스트캠퍼스 챌린지 16일차 (0) 2021.11.16