Last active
February 19, 2020 09:09
-
-
Save kazuhito-m/f5111eaf9c42676bc740e58c90bcdfb8 to your computer and use it in GitHub Desktop.
SpringELのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import org.springframework.expression.Expression; | |
import org.springframework.expression.ExpressionParser; | |
import org.springframework.expression.common.TemplateParserContext; | |
import org.springframework.expression.spel.standard.SpelExpressionParser; | |
import org.springframework.expression.spel.support.StandardEvaluationContext; | |
import java.util.HashMap; | |
import java.util.Map; | |
import static org.assertj.core.api.Assertions.assertThat; | |
public class SpringELTest { | |
@Test | |
public void springElで任意の変数が使えるかのテスト() { | |
// String template = "できる!${originalCaption}"; 本当にしたいのはこれだが…無理みたい | |
String template = "できる!${#originalCaption}"; | |
ExpressionParser parser = new SpelExpressionParser(); | |
Expression exp = parser.parseExpression(template, new TemplateParserContext("${", "}")); | |
StandardEvaluationContext context = new StandardEvaluationContext(); | |
context.setVariable("originalCaption", "Hello World"); | |
String message = exp.getValue(context, String.class); | |
assertThat(message).isEqualTo("できる!Hello World"); | |
} | |
@Test | |
public void スタックオーバーフローの例() { | |
Map<String, Object> data = new HashMap<>(); | |
data.put("property", 123); | |
String template = "Some text: #{#data['property']}"; | |
ExpressionParser parser = new SpelExpressionParser(); | |
Expression expression = parser.parseExpression(template, new TemplateParserContext()); | |
StandardEvaluationContext context = new StandardEvaluationContext(); | |
context.setVariable("data", data); | |
String actual = expression.getValue(context, String.class); | |
assertThat(actual).isEqualTo("Some text: 123"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment