반응형

SpEL(Spring Expresion Language)이란?

  • 런타임시에 객체 그래프를 조회하고 조작하는 언어를 말한다.

기본 문법

/*
    ex)
    - "1 + 1"                       // 2
    - "(1 + 1) * 2 - 3"             // 1
    - "'hello' + 'world'"           // helloworld
    - "'Hello World'.length"        // 11
    - "'Hello World'.concat('!')"   // Hello World!
    - "'Hello World'.toUpperCase()" // HELLO WORLD
    - "'Hello'.bytes"               // 72,101,108,108,111
    - "1 eq 1"                      // true
    - "1 == 1"                      // true
    - "!true"                       // false
    - "'100' matches '\\d+'"        // true
    - "'100abcd' matches '\\d+'"    // false
    - "T(java.lang.Math).random()"  // 랜덤 넘버
    */
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("'1 + 1");
String result = expression.getValue(String.class);
System.out.println(result); // 2

context variable 활용

SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();

context.setVariable("name", "tyler");
context.setVariable("age", 50);

String info = parser.parseExpression("#name + #age").getValue(context, String.class);
System.out.println(info); // tyler50

 

객체 필드 조회

@Setter
@Getter
@AllArgsConstructor
private static class User {
    private String name;
    private int age;
}
User user = new User("tyler", 50);
EvaluationContext context = new StandardEvaluationContext(user);

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("name + age");

String userInfo1 = expression.getValue(context, String.class);
String userInfo2 = expression.getValue(user, String.class);

System.out.println(userInfo1); // tyler50
System.out.println(userInfo2); // tyler50

객체 필드 조작

User user = new User("tyler", 50);
EvaluationContext context = new StandardEvaluationContext(user);

ExpressionParser parser = new SpelExpressionParser();
parser.parseExpression("name").setValue(context, "john");

System.out.println(user.name); // john

리스트 조회

List<User> users = List.of(
    new User("tyler", 50),
    new User("john", 100)
);

EvaluationContext context = new StandardEvaluationContext(users);

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("[0]");

User user = expression.getValue(context, User.class);

System.out.println(user.name); // tyler
반응형

'Development > Spring' 카테고리의 다른 글

[Spring] 헥사고날 아키텍처(Hexagonal Architecture)  (2) 2023.11.23
[Spring] WireMock  (0) 2023.08.18
[Spring] actuator  (0) 2021.11.27
[Spring] Scheduler Lock  (0) 2021.11.25
[Spring] Replication  (0) 2021.11.15

+ Recent posts