SpEL(스프링 Expression Language)

| 스프링 EL 이란 ?

  • JSP의 EL 과 비슷하다
  • 객체 그래프를 조회하고 조작하는 기능을 제공
  • Unified EL과 비슷하지만, 메소드 호출을 지원하며 문자열 템플릿 기능도 제공한다
  • OGNL, JBOSS EL 등 자바에서 사용할 수 있는 EL이 있지만 SpEL은 모든 스프링 프로젝트 전반에 걸쳐 상요할 EL로 만들었다.
  • 스프링 3.0부터 지원

Spel 구성

  • ExpressionParser parser = new SpelExpressionParser()
  • StandardEvaluationContext context = new StandardEvaluationContext(bean)
  • Expression expression = parser.parseExpression("SpEL 표현식")
  • String value = expression.getvalue(context, String.class)

문법

  • #{"표현식"}
  • ${"프로퍼티"}
  • 표현식은 프로퍼티를 가질 수 있지만 반되는 안됨

쓰이는 곳

  • @Value 애노테이션
  • @ConditionalOnExpression 애노테이션
  • 스프링 시큐리티, 스프링 데이터, Thymeleaf 등

 

소스

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
import org.springframework.stereotype.Component;

@Component
public class Sample {

    private int data = 200;

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
}
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
 import org.springframework.expression.Expression;
 import org.springframework.expression.ExpressionParser;
 import org.springframework.expression.spel.standard.SpelExpressionParser;
 import org.springframework.stereotype.Component;


@Component
public class AppRunner implements ApplicationRunner {


    @Value("#{1 + 1}")
    int value;

    @Value("#{'hello ' + 'world'}")
    String greeting;

    @Value("#{1 eq 1}")
    boolean trueOrFalse;

    @Value("hello")
    String hello;

    // 클래스의 값을 가져올 수도 있다.
    @Value("#{sample.data}")
    int sampleData;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("===================");
        System.out.println(value);
        System.out.println(greeting);
        System.out.println(trueOrFalse);
        System.out.println(hello);
        System.out.println(sampleData);

        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression("2 + 100");
        Integer value = expression.getValue(Integer.class);
        System.out.println(value);

    }
}

결과

2
hello world
true
hello
200
102

'📚 Spring > Spring 개념' 카테고리의 다른 글

Spring AOP : @AOP  (0) 2020.11.24
Spring AOP : 프록시 기반 AOP  (0) 2020.11.20
데이터 바인딩 추상화 : Converter와 Formatter  (0) 2020.10.05
데이터 바인딩 추상화 : PropertyEditor  (0) 2020.09.14
Resource 추상화  (0) 2020.09.14

댓글

Designed by JB FACTORY