스프링의 표현 언어(SpEL)

박근수·2024년 2월 24일
0

Spring

목록 보기
6/11

💡 Expression Laguage(표현언어)는 짧고 간단한 문법을 통해 필요한 데이터나 설정 값을 얻어올 수 있게 하는 특별한 형태의 표현식에 가까운 간편한 언어(그래프 접근 가능)

SpEL의 값 평가(evalution)

  • SpelParser 는 "" 안에 들어있는 문자열을 평가(evaluation) 해서 결과값을 만들어낸다.
  • "Hello World" 는 문자열 리터럴이 되며, concat이라는 메서드도 호출할 수 있다.
  • String 객체를 new로 생성해서 사용도 가능
ExpressionParser parser = new SpelExpressParser();
Expression exp = parser.parseExpression("'Hello Wordl'");
String messag = (String) exp.getValue(); //"Hello World"

Expression expWow = parser.parseExpression("'Hello Wordl'.concat('!')");
String messageWow = (String) expWow.getValue(); //"Hello Wordl!";

Expressiom expString = parser.parseExpression("new String('hello world').toUpperCase()");s
String messageString = expString.getValue(String.class); // "HELLO WORDL"

Bean의 Property를 설정할 때 사용하는 방식

  • 기본적으로 #{ } 방식으로 property를 설정
  • application.properties(또는 application.yml)의 값을 가져올 때는 ${ } 방식으로 가져옴
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
}
profile
개발블로그

0개의 댓글