Java/Spring framework

Spring framework core (11) - SpEL

감동이중요해 2020. 1. 24. 22:44

SpEL (Spring Expression Language

런타임 시간에 작동하는 강력한 표현 언어로, Spring 하위 프로젝트에서 주로 사용된다.

구성

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("5 * 5");
int expVal = exp.getValue(Integer.class);
System.out.println(expVal);

주요 문법

  1. ${"property_name"}

    • $ 로 시작하며, property 값을 읽어올 수 있다.
  2. #{"expression"}

    • # 로 시작하며, 1+1(덧셈), 1 eq 1(참/거짓 판별) 등 표현식을 사용하여 나타낼 수 있다.

    • expression은 property를 참조할 수 있다.

      • #{"${hello} world"} 를 사용하면 ${hello}가 해석된 뒤 world를 붙이는 식이다.

사용처

  1. @Value
  2. @ConditionalOnExpreesion
  3. Spring Security
    • @PostFilter 등 설정에 사용하는 Annotation
    • XML 설정
  4. Spring data
    • @Query

사용 예시

Spring Boot 프로젝트를 생성하고 코드를 작성한다.

  1. AppRunner
@Component
public class AppRunner implements ApplicationRunner {

    @Value("#{1 + 1}") // #{} 표현식 1
    private int val1;

    @Value("#{1 * 2}") // #{} 표현식 2
    private int val2;

    @Value("#{1 eq 1}") // #{} 표현식 3
    private boolean val3;

    // property 불러오기
    // hello가 없으면 : 뒤에 있는 요소를 default값으로 인식
    @Value("${hello:default hello}")
    private String hello;

    // #{} 내부에 ${} 사용하기
    @Value("#{'${hello} world'}")
    private String helloWorld;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("5 * 5");
        int expVal = exp.getValue(Integer.class);
        System.out.println(expVal);

        System.out.println(val1);
        System.out.println(val2);
        System.out.println(val3);
        System.out.println(hello);
        System.out.println(helloWorld);
    }
}

 

전체 소스코드

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