Java Reference
In-Depth Information
A common scenario is evaluation of expressions against an object. The properties and methods of
the object no longer require an instance or class, and can be manipulated independently. The SpEL
parser refers to it as the root object . Let's take an object named SocialNetworkingSiteContext , for
example, which in turn has other attributes you want to traverse to iterate over the members of the site:
SocialNetworkingSiteContext socialNetworkingSiteContext =
new SocialNetworkingSiteContext();
// ... ensure it's properly initialized ...
Expression firstNameExpression = parser.parseExpression("loggedInUser.firstName");
StandardEvaluationContext ctx = new StandardEvaluationContext();
String valueOfLoggedInUserFirstName = exp.getValue(ctx, String.class );
Because you set the socialNetworkingSiteContext as the root, you could enumerate any child
property without qualifying the reference.
Suppose that instead of specifying a root object you want to specify a named variable and be
able to access it from within your expression. The SpEL parser lets you provide it with variables
against which expressions can be evaluated. In the following example, you provide it with a
socialNetworkingSiteContext variable. Inside the expression, the variable is prefixed with a "#" :
StandardEvaluationContext ctx1 = new StandardEvaluationContext ();
SocialNetworkingSiteContext socialNetworkingSiteContext =
new SocialNetworkingSiteContext();
Friend myFriend = new Friend() ;
socialNetworkingSiteContext );
Expression loggedInUserFirstNameExpression =
String loggedInUserFirstName = loggedInUserFirstName Expression.getValue(ctx1,
Similarly, you can provide the expression language named functions that are available without any
qualification inside an expression:
StandardEvaluationContext ctx1 = new StandardEvaluationContext();
"isEmpty", new Class[] { String.class }));
Expression functionEval = parser.parseExpression(
" #empty(null) ? 'empty' : 'not empty' ");
String result = functionEval.getValue(ctx1, String.class );
You can use the expression language parser infrastructure to template String s. The returned
value is a String , although within the String you can have the parser substitute the result of evaluated
expressions. This could be useful in any number of scenarios—for example, in simple message
preparation. You simply create an instance of org.springframework.expression.ParserContext . This
class dictates to the parser which token is prefix (the prefix token is "${") and which is a suffix (the suffix
token is "}" ). The following example yields "The millisecond is 1246953975093" .
Search WWH ::

Custom Search