Skip to content

Instantly share code, notes, and snippets.

@thekalinga
Last active March 3, 2019 08:47
Show Gist options
  • Save thekalinga/2a6ed4eeff8ebe290bc4b7e13089da9f to your computer and use it in GitHub Desktop.
Save thekalinga/2a6ed4eeff8ebe290bc4b7e13089da9f to your computer and use it in GitHub Desktop.
SPEL in a nutshell
class RootObject {
  private String prop;
  private Child child;
}

// with root object
JavaExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression("prop + #var + 'somethingelse'");
RootObject rootObject = new RootObject("whatever");
EvaluationContext context = new StandardEvaluationContext(rootObject);
context.setVariable("var", "var val");
String result = expression.getValue(context, String.class);

Basics

  • @Value("#{...}") - Basic format for property binding in Spring, which comes from StandardBeanExpressionResolver which has expressionPrefix as #{ & sufix as }

Within the expressions (#{...here...})

  • T(fqcn.MyClass).staticMethod(..) - For accessing java Class object
  • @myBeanRef.prop - For accessing beans from application context if context is configured with a custom BeanResolver via context.setBeanResolver(new MyBeanResolver());
  • #0, #methodParam, #customVar - Variables set via context.setVariable("0", "val") format can be accessed using # within
  • child.prop") - Accessing child of rootObject set within evaluation context
  • obj?.nullableProp?.deeperNullableProp") - Null safe navigation
  • booleanVar ?: 'Hello'") - Elvis operator supported
  • collection[1]") - Index based collection element access
  • map['key']") - Access map value based on Key
  • obj.method('val')") - Method execution against the child
  • methodOnRoot('val')") - Method execution against root object
  • ${custom.property}") - Access environment properties in spring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment