core-expressions.adoc 49.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
[[expressions]]
= Spring Expression Language (SpEL)




[[expressions-intro]]
== Introduction
The Spring Expression Language (SpEL for short) is a powerful expression language that
supports querying and manipulating an object graph at runtime. The language syntax is
similar to Unified EL but offers additional features, most notably method invocation and
basic string templating functionality.

While there are several other Java expression languages available, OGNL, MVEL, and JBoss
EL, to name a few, the Spring Expression Language was created to provide the Spring
community with a single well supported expression language that can be used across all
the products in the Spring portfolio. Its language features are driven by the
requirements of the projects in the Spring portfolio, including tooling requirements for
code completion support within the eclipse based Spring Tool Suite. That said,
SpEL is based on a technology agnostic API allowing other expression language
implementations to be integrated should the need arise.

While SpEL serves as the foundation for expression evaluation within the Spring
portfolio, it is not directly tied to Spring and can be used independently. In order to
be self contained, many of the examples in this chapter use SpEL as if it were an
independent expression language. This requires creating a few bootstrapping
infrastructure classes such as the parser. Most Spring users will not need to deal with
this infrastructure and will instead only author expression strings for evaluation. An
example of this typical use is the integration of SpEL into creating XML or annotated
based bean definitions as shown in the section <<expressions-beandef,Expression support
for defining bean definitions.>>

This chapter covers the features of the expression language, its API, and its language
syntax. In several places an Inventor and Inventor's Society class are used as the
target objects for expression evaluation. These class declarations and the data used to
populate them are listed at the end of the chapter.




[[expressions-features]]
== Feature Overview
The expression language supports the following functionality

* Literal expressions
* Boolean and relational operators
* Regular expressions
* Class expressions
* Accessing properties, arrays, lists, maps
* Method invocation
* Relational operators
* Assignment
* Calling constructors
* Bean references
* Array construction
* Inline lists
* Inline maps
* Ternary operator
* Variables
* User defined functions
* Collection projection
* Collection selection
* Templated expressions




[[expressions-evaluation]]
== Expression Evaluation using Spring's Expression Interface
This section introduces the simple use of SpEL interfaces and its expression language.
The complete language reference can be found in the section
<<expressions-language-ref,Language Reference>>.

The following code introduces the SpEL API to evaluate the literal string expression
'Hello World'.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
S
Sam Brannen 已提交
81
	Expression exp = parser.parseExpression("**'Hello World'**");
82 83 84 85 86 87 88 89 90 91 92 93
	String message = (String) exp.getValue();
----

The value of the message variable is simply 'Hello World'.

The SpEL classes and interfaces you are most likely to use are located in the packages
`org.springframework.expression` and its sub packages and `spel.support`.

The interface `ExpressionParser` is responsible for parsing an expression string. In
this example the expression string is a string literal denoted by the surrounding single
quotes. The interface `Expression` is responsible for evaluating the previously defined
expression string. There are two exceptions that can be thrown, `ParseException` and
S
Sam Brannen 已提交
94
`EvaluationException` when calling `parser.parseExpression` and `exp.getValue`
95 96 97 98 99
respectively.

SpEL supports a wide range of features, such as calling methods, accessing properties,
and calling constructors.

S
Sam Brannen 已提交
100
As an example of method invocation, we call the `concat` method on the string literal.
101 102 103 104 105

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
S
Sam Brannen 已提交
106
	Expression exp = parser.parseExpression("**'Hello World'.concat('!')**");
107 108 109 110 111
	String message = (String) exp.getValue();
----

The value of message is now 'Hello World!'.

S
Sam Brannen 已提交
112
As an example of calling a JavaBean property, the String property `Bytes` can be called
113 114 115 116 117 118 119 120
as shown below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	// invokes 'getBytes()'
S
Sam Brannen 已提交
121
	Expression exp = parser.parseExpression("**'Hello World'.bytes**");
122 123 124
	byte[] bytes = (byte[]) exp.getValue();
----

S
Sam Brannen 已提交
125
SpEL also supports nested properties using standard _dot_ notation, i.e.
126 127 128 129 130 131 132 133 134 135
prop1.prop2.prop3 and the setting of property values

Public fields may also be accessed.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	// invokes 'getBytes().length'
S
Sam Brannen 已提交
136
	Expression exp = parser.parseExpression("**'Hello World'.bytes.length**");
137 138 139 140 141 142 143 144 145
	int length = (Integer) exp.getValue();
----

The String's constructor can be called instead of using a string literal.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
S
Sam Brannen 已提交
146
	Expression exp = parser.parseExpression("**new String('hello world').toUpperCase()**");
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	String message = exp.getValue(String.class);
----

Note the use of the generic method `public <T> T getValue(Class<T> desiredResultType)`.
Using this method removes the need to cast the value of the expression to the desired
result type. An `EvaluationException` will be thrown if the value cannot be cast to the
type `T` or converted using the registered type converter.

The more common usage of SpEL is to provide an expression string that is evaluated
against a specific object instance (called the root object). There are two options here
and which to choose depends on whether the object against which the expression is being
evaluated will be changing with each call to evaluate the expression. In the following
example we retrieve the `name` property from an instance of the Inventor class.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// Create and set a calendar
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);

	// The constructor arguments are name, birthday, and nationality.
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression("**name**");

	EvaluationContext context = new StandardEvaluationContext(tesla);
	String name = (String) exp.getValue(context);
----

S
Sam Brannen 已提交
178
In the last line, the value of the string variable `name` will be set to "Nikola Tesla".
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
The class StandardEvaluationContext is where you can specify which object the "name"
property will be evaluated against. This is the mechanism to use if the root object is
unlikely to change, it can simply be set once in the evaluation context. If the root
object is likely to change repeatedly, it can be supplied on each call to `getValue`, as
this next example shows:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	/ Create and set a calendar
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);

	// The constructor arguments are name, birthday, and nationality.
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression("**name**");
	String name = (String) exp.getValue(tesla);
----

In this case the inventor `tesla` has been supplied directly to `getValue` and the
expression evaluation infrastructure creates and manages a default evaluation context
internally - it did not require one to be supplied.

The StandardEvaluationContext is relatively expensive to construct and during repeated
usage it builds up cached state that enables subsequent expression evaluations to be
performed more quickly. For this reason it is better to cache and reuse them where
possible, rather than construct a new one for each expression evaluation.

In some cases it can be desirable to use a configured evaluation context and yet still
supply a different root object on each call to `getValue`. `getValue` allows both to be
specified on the same call. In these situations the root object passed on the call is
considered to override any (which maybe null) specified on the evaluation context.

[NOTE]
====
In standalone usage of SpEL there is a need to create the parser, parse expressions and
perhaps provide evaluation contexts and a root context object. However, more common
usage is to provide only the SpEL expression string as part of a configuration file, for
example for Spring bean or Spring Web Flow definitions. In this case, the parser,
evaluation context, root object and any predefined variables are all set up implicitly,
requiring the user to specify nothing other than the expressions.
====
223

224 225 226 227 228 229
As a final introductory example, the use of a boolean operator is shown using the
Inventor object in the previous example.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
S
Sam Brannen 已提交
230
	Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
231 232 233 234 235 236 237 238 239 240
	boolean result = exp.getValue(context, Boolean.class); // evaluates to true
----



[[expressions-evaluation-context]]
=== The EvaluationContext interface
The interface `EvaluationContext` is used when evaluating an expression to resolve
properties, methods, fields, and to help perform type conversion. The out-of-the-box
implementation, `StandardEvaluationContext`, uses reflection to manipulate the object,
S
Sam Brannen 已提交
241 242
caching `java.lang.reflect.Method`, `java.lang.reflect.Field`, and
`java.lang.reflect.Constructor` instances for increased performance.
243 244 245 246 247 248 249 250

The `StandardEvaluationContext` is where you may specify the root object to evaluate
against via the method `setRootObject()` or passing the root object into the
constructor. You can also specify variables and functions that will be used in the
expression using the methods `setVariable()` and `registerFunction()`. The use of
variables and functions are described in the language reference sections
<<expressions-ref-variables,Variables>> and <<expressions-ref-functions,Functions>>. The
`StandardEvaluationContext` is also where you can register custom
S
Sam Brannen 已提交
251
``ConstructorResolver``s, ``MethodResolver``s, and ``PropertyAccessor``s to extend how SpEL
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
evaluates expressions. Please refer to the JavaDoc of these classes for more details.


[[expressions-type-conversion]]
==== Type Conversion
By default SpEL uses the conversion service available in Spring core (
`org.springframework.core.convert.ConversionService`). This conversion service comes
with many converters built in for common conversions but is also fully extensible so
custom conversions between types can be added. Additionally it has the key capability
that it is generics aware. This means that when working with generic types in
expressions, SpEL will attempt conversions to maintain type correctness for any objects
it encounters.

What does this mean in practice? Suppose assignment, using `setValue()`, is being used
to set a `List` property. The type of the property is actually `List<Boolean>`. SpEL
will recognize that the elements of the list need to be converted to `Boolean` before
being placed in it. A simple example:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	class Simple {
		public List<Boolean> booleanList = new ArrayList<Boolean>();
	}

	Simple simple = new Simple();

	simple.booleanList.add(true);

	StandardEvaluationContext simpleContext = new StandardEvaluationContext(simple);

	// false is passed in here as a string. SpEL and the conversion service will
	// correctly recognize that it needs to be a Boolean and convert it
	parser.parseExpression("booleanList[0]").setValue(simpleContext, "false");

	// b will be false
	Boolean b = simple.booleanList.get(0);
----

[[expressions-parser-configuration]]
=== Parser configuration
It is possible to configure the SpEL expression parser using a parser configuration object 
(`org.springframework.expression.spel.SpelParserConfiguration`). The configuration
S
Sam Brannen 已提交
295
object controls the behavior of some of the expression components. For example, if
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
indexing into an array or collection and the element at the specified index is `null`
it is possible to automatically create the element. This is useful when using expressions made up of a
chain of property references. If indexing into an array or list
and specifying an index that is beyond the end of the current size of the array or
list it is possible to automatically grow the array or list to accommodate that index.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	class Demo {
		public List<String> list;
	}
	
	// Turn on:
	// - auto null reference initialization
	// - auto collection growing
	SpelParserConfiguration config = new SpelParserConfiguration(true,true);

	ExpressionParser parser = new SpelExpressionParser(config);

	Expression expression = parser.parseExpression("list[3]");

	Demo demo = new Demo();

	Object o = expression.getValue(demo);

	// demo.list will now be a real collection of 4 entries
	// Each entry is a new empty String
----

It is also possible to configure the behaviour of the SpEL expression compiler.

[[expressions-spel-compilation]]
=== SpEL compilation

Spring Framework 4.1 includes a basic expression compiler. Expressions are usually
interpreted which provides a lot of dynamic flexibility during evaluation but
does not provide the optimum performance. For occasional expression usage
this is fine, but when used by other components like Spring Integration, 
performance can be very important and there is no real need for the dynamism.

The new SpEL compiler is intended to address this need. The 
compiler will generate a real Java class on the fly during evaluation that embodies the
S
Sam Brannen 已提交
339
expression behavior and use that to achieve much faster expression
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
evaluation. Due to the lack of typing around expressions the compiler
uses information gathered during the interpreted evaluations of an
expression when performing compilation. For example, it does not know the type
of a property reference purely from the expression but during the first
interpreted evaluation it will find out what it is. Of course, basing the 
compilation on this information could cause trouble later if the types of
the various expression elements change over time. For this reason compilation
is best suited to expressions whose type information is not going to change
on repeated evaluations.

For a basic expression like this:

`someArray[0].someProperty.someOtherProperty < 0.1`

which involves array access, some property derefencing and numeric operations, the performance
S
Sam Brannen 已提交
355
gain can be very noticeable. In an example micro benchmark run of 50000 iterations, it was
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
taking 75ms to evaluate using only the interpreter and just 3ms using the compiled version
of the expression.

[[expressions-compiler-configuration]]
==== Compiler configuration

The compiler is not turned on by default, but there are two ways to turn
it on. It can be turned on using the parser configuration process discussed earlier or
via a system property when SpEL usage is embedded inside another component. This section
discusses both of these options.

Is is important to understand that there are a few modes the compiler can operate in, captured
in an enum (`org.springframework.expression.spel.SpelCompilerMode`). The modes are as follows:

- `OFF` - The compiler is switched off; this is the default.
- `IMMEDIATE` - In immediate mode the expressions are compiled as soon as possible. This
is typically after the first interpreted evaluation. If the compiled expression fails
(typically due to a type changing, as described above) then the caller of the expression
evaluation will receive an exception.
- `MIXED` - In mixed mode the expressions silently switch between interpreted and compiled
mode over time.  After some number of interpreted runs they will switch to compiled
form and if something goes wrong with the compiled form (like a type changing, as
described above) then the expression will automatically switch back to interpreted form
again. Sometime later it may generate another compiled form and switch to it. Basically
the exception that the user gets in `IMMEDIATE` mode is instead handled internally.

`IMMEDIATE` mode exists because `MIXED` mode could cause issues for expressions that
have side effects. If a compiled expression blows up after partially succeeding it
may have already done something that has affected the state of the system. If this
has happened the caller may not want it to silently re-run in interpreted mode
since part of the expression may be running twice.

After selecting a mode, use the `SpelParserConfiguration` to configure the parser:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE,
		this.getClass().getClassLoader());

	SpelExpressionParser parser = new SpelExpressionParser(config);

	Expression expr = parser.parseExpression("payload");

	MyMessage message = new MyMessage();

	Object payload = expr.getValue(message);
----

When specifying the compiler mode it is also possible to specify a classloader (passing null is allowed).
Compiled expressions will be defined in a child classloader created under any that is supplied.
It is important to ensure if a classloader is specified it can see all the types involved in
the expression evaluation process.
If none is specified then a default classloader will be used (typically the context classloader for
the thread that is running during expression evaluation).

The second way to configure the compiler is for use when SpEL is embedded inside some other
component and it may not be possible to configure via a configuration object.
In these cases it is possible to use a system property. The property 
`spring.expression.compiler.mode` can be set to one of the `SpelCompilerMode` 
S
Sam Brannen 已提交
416
enum values (`off`, `immediate`, or `mixed`).
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

[[expressions-compiler-limitations]]
==== Compiler limitations

With Spring Framework 4.1 the basic compilation framework is in place. However, the framework does not
yet support compiling every kind of expression. The initial focus has been on the common expressions that are
likely to be used in performance critical contexts.  These kinds of expression cannot be compiled
at the moment:

- expressions involving assignment 
- expressions relying on the conversion service
- expressions using custom resolvers or accessors
- expressions using selection or projection

More and more types of expression will be compilable in the future.

[[expressions-beandef]]
== Expression support for defining bean definitions
SpEL expressions can be used with XML or annotation-based configuration metadata for
S
Sam Brannen 已提交
436
defining ``BeanDefinition``s. In both cases the syntax to define the expression is of the
437 438 439 440 441 442 443 444 445
form `#{ <expression string> }`.



[[expressions-beandef-xml-based]]
=== XML based configuration
A property or constructor-arg value can be set using expressions as shown below.

[source,xml,indent=0]
S
Stephane Nicoll 已提交
446
[subs="verbatim"]
447 448 449 450 451 452 453 454 455 456 457 458 459
----
	<bean id="numberGuess" class="org.spring.samples.NumberGuess">
		<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>

		<!-- other properties -->
	</bean>
----

The variable `systemProperties` is predefined, so you can use it in your expressions as
shown below. Note that you do not have to prefix the predefined variable with the `#`
symbol in this context.

[source,xml,indent=0]
S
Stephane Nicoll 已提交
460
[subs="verbatim"]
461 462
----
	<bean id="taxCalculator" class="org.spring.samples.TaxCalculator">
S
Sam Brannen 已提交
463
		<property name="defaultLocale" value="#{ systemProperties['user.region'] }"/>
464 465 466 467 468 469 470 471

		<!-- other properties -->
	</bean>
----

You can also refer to other bean properties by name, for example.

[source,xml,indent=0]
S
Stephane Nicoll 已提交
472
[subs="verbatim"]
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
----
	<bean id="numberGuess" class="org.spring.samples.NumberGuess">
		<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>

		<!-- other properties -->
	</bean>

	<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
		<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>

		<!-- other properties -->
	</bean>
----



[[expressions-beandef-annotation-based]]
=== Annotation-based configuration
The `@Value` annotation can be placed on fields, methods and method/constructor
parameters to specify a default value.

Here is an example to set the default value of a field variable.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public static class FieldValueTestBean

S
Sam Brannen 已提交
501
		@Value("#{ systemProperties['user.region'] }")
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
		private String defaultLocale;

		public void setDefaultLocale(String defaultLocale) {
			this.defaultLocale = defaultLocale;
		}

		public String getDefaultLocale() {
			return this.defaultLocale;
		}

	}
----

The equivalent but on a property setter method is shown below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public static class PropertyValueTestBean

		private String defaultLocale;

S
Sam Brannen 已提交
524
		@Value("#{ systemProperties['user.region'] }")
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
		public void setDefaultLocale(String defaultLocale) {
			this.defaultLocale = defaultLocale;
		}

		public String getDefaultLocale() {
			return this.defaultLocale;
		}

	}
----

Autowired methods and constructors can also use the `@Value` annotation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public class SimpleMovieLister {

		private MovieFinder movieFinder;
		private String defaultLocale;

		@Autowired
		public void configure(MovieFinder movieFinder,
S
Sam Brannen 已提交
548
				@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
			this.movieFinder = movieFinder;
			this.defaultLocale = defaultLocale;
		}

		// ...
	}
----

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public class MovieRecommender {

		private String defaultLocale;

		private CustomerPreferenceDao customerPreferenceDao;

		@Autowired
		public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
S
Sam Brannen 已提交
568
				@Value("#{systemProperties['user.country']}") String defaultLocale) {
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
			this.customerPreferenceDao = customerPreferenceDao;
			this.defaultLocale = defaultLocale;
		}

		// ...
	}
----




[[expressions-language-ref]]
== Language Reference



[[expressions-ref-literal]]
=== Literal expressions
587 588 589 590 591 592 593
The types of literal expressions supported are strings, numeric values (int, real, hex),
boolean and null. Strings are delimited by single quotes. To put a single quote itself
in a string, use two single quote characters.

The following listing shows simple usage of literals. Typically they would not be used
in isolation like this but rather as part of a more complex expression, for example
using a literal on one side of a logical comparison operator.
594 595 596 597 598 599 600

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	// evals to "Hello World"
S
Sam Brannen 已提交
601
	String helloWorld = (String) parser.parseExpression("'Hello World'").getValue();
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

	double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue();

	// evals to 2147483647
	int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue();

	boolean trueValue = (Boolean) parser.parseExpression("true").getValue();

	Object nullValue = parser.parseExpression("null").getValue();
----

Numbers support the use of the negative sign, exponential notation, and decimal points.
By default real numbers are parsed using Double.parseDouble().



[[expressions-properties-arrays]]
=== Properties, Arrays, Lists, Maps, Indexers
Navigating with property references is easy: just use a period to indicate a nested
property value. The instances of the `Inventor` class, pupin, and tesla, were populated with
data listed in the section <<expressions-example-classes,Classes used in the examples>>.
To navigate "down" and get Tesla's year of birth and Pupin's city of birth the following
expressions are used.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// evals to 1856
	int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context);

	String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);
----

Case insensitivity is allowed for the first letter of property names. The contents of
arrays and lists are obtained using square bracket notation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	// Inventions Array
	StandardEvaluationContext teslaContext = new StandardEvaluationContext(tesla);

	// evaluates to "Induction motor"
	String invention = parser.parseExpression("inventions[3]").getValue(
			teslaContext, String.class);

	// Members List
	StandardEvaluationContext societyContext = new StandardEvaluationContext(ieee);

	// evaluates to "Nikola Tesla"
	String name = parser.parseExpression("Members[0].Name").getValue(
			societyContext, String.class);

	// List and Array navigation
	// evaluates to "Wireless communication"
	String invention = parser.parseExpression("Members[0].Inventions[6]").getValue(
			societyContext, String.class);
----

The contents of maps are obtained by specifying the literal key value within the
brackets. In this case, because keys for the Officers map are strings, we can specify
string literals.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// Officer's Dictionary

S
Sam Brannen 已提交
672
	Inventor pupin = parser.parseExpression("Officers['president']").getValue(
673 674 675
			societyContext, Inventor.class);

	// evaluates to "Idvor"
S
Sam Brannen 已提交
676
	String city = parser.parseExpression("Officers['president'].PlaceOfBirth.City").getValue(
677 678 679
			societyContext, String.class);

	// setting values
S
Sam Brannen 已提交
680
	parser.parseExpression("Officers['advisors'][0].PlaceOfBirth.Country").setValue(
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
			societyContext, "Croatia");
----



[[expressions-inline-lists]]
=== Inline lists
Lists can be expressed directly in an expression using `{}` notation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// evaluates to a Java list containing the four numbers
	List numbers = (List) parser.parseExpression("{1,2,3,4}").getValue(context);

S
Sam Brannen 已提交
696
	List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context);
697 698 699 700 701 702 703 704 705 706 707 708 709 710
----

`{}` by itself means an empty list. For performance reasons, if the list is itself
entirely composed of fixed literals then a constant list is created to represent the
expression, rather than building a new list on each evaluation.

[[expressions-inline-maps]]
=== Inline Maps
Maps can also be expressed directly in an expression using `{key:value}` notation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// evaluates to a Java map containing the two entries
S
Sam Brannen 已提交
711
	Map inventorInfo = (Map) parser.parseExpression("{name:'Nikola',dob:'10-July-1856'}").getValue(context);
712

S
Sam Brannen 已提交
713
	Map mapOfMaps = (Map) parser.parseExpression("{name:{first:'Nikola',last:'Tesla'},dob:{day:10,month:'July',year:1856}}").getValue(context);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
----
`{:}` by itself means an empty map. For performance reasons, if the map is itself composed
of fixed literals or other nested constant structures (lists or maps) then a constant map is created
to represent the expression, rather than building a new map on each evaluation. Quoting of the map keys
is optional, the examples above are not using quoted keys.

[[expressions-array-construction]]
=== Array construction
Arrays can be built using the familiar Java syntax, optionally supplying an initializer
to have the array populated at construction time.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	int[] numbers1 = (int[]) parser.parseExpression("new int[4]").getValue(context);

	// Array with initializer
	int[] numbers2 = (int[]) parser.parseExpression("new int[]{1,2,3}").getValue(context);

	// Multi dimensional array
	int[][] numbers3 = (int[][]) parser.parseExpression("new int[4][5]").getValue(context);
----

It is not currently allowed to supply an initializer when constructing a
multi-dimensional array.



[[expressions-methods]]
=== Methods
Methods are invoked using typical Java programming syntax. You may also invoke methods
on literals. Varargs are also supported.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// string literal, evaluates to "bc"
S
Sam Brannen 已提交
751
	String c = parser.parseExpression("'abc'.substring(2, 3)").getValue(String.class);
752 753

	// evaluates to true
S
Sam Brannen 已提交
754
	boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
			societyContext, Boolean.class);
----



[[expressions-operators]]
=== Operators


[[expressions-operators-relational]]
==== Relational operators
The relational operators; equal, not equal, less than, less than or equal, greater than,
and greater than or equal are supported using standard operator notation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// evaluates to true
	boolean trueValue = parser.parseExpression("2 == 2").getValue(Boolean.class);

	// evaluates to false
	boolean falseValue = parser.parseExpression("2 < -5.0").getValue(Boolean.class);

	// evaluates to true
S
Sam Brannen 已提交
779
	boolean trueValue = parser.parseExpression("'black' < 'block'").getValue(Boolean.class);
780 781
----

782 783 784 785 786 787 788 789 790 791 792
[NOTE]
====
Greater/less-than comparisons against `null` follow a simple rule: `null` is treated as
nothing here (i.e. NOT as zero). As a consequence, any other value is always greater
than `null` (`X > null` is always `true`) and no other value is ever less than nothing
(`X < null` is always `false`).

If you prefer numeric comparisons instead, please avoid number-based `null` comparisons
in favor of comparisons against zero (e.g. `X > 0` or `X < 0`).
====

793 794 795 796 797 798 799 800
In addition to standard relational operators SpEL supports the `instanceof` and regular
expression based `matches` operator.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// evaluates to false
	boolean falseValue = parser.parseExpression(
S
sylvainlaurent 已提交
801
			"'xyz' instanceof T(Integer)").getValue(Boolean.class);
802 803 804

	// evaluates to true
	boolean trueValue = parser.parseExpression(
S
Sam Brannen 已提交
805
			"'5.00' matches '\^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
806 807 808

	//evaluates to false
	boolean falseValue = parser.parseExpression(
S
Sam Brannen 已提交
809
			"'5.0067' matches '\^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
810 811
----

S
Stephane Nicoll 已提交
812 813 814
[NOTE]
====
Be careful with primitive types as they are immediately boxed up to the wrapper type,
S
sylvainlaurent 已提交
815
so `1 instanceof T(int)` evaluates to `false` while `1 instanceof T(Integer)`
S
Stephane Nicoll 已提交
816 817 818
evaluates to `true`, as expected.
====

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
Each symbolic operator can also be specified as a purely alphabetic equivalent. This
avoids problems where the symbols used have special meaning for the document type in
which the expression is embedded (eg. an XML document). The textual equivalents are
shown here: `lt` (`<`), `gt` (`>`), `le` (`<=`), `ge` (`>=`), `eq` (`==`),
`ne` (`!=`), `div` (`/`), `mod` (`%`), `not` (`!`). These are case insensitive.


[[expressions-operators-logical]]
==== Logical operators
The logical operators that are supported are and, or, and not. Their use is demonstrated
below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// -- AND --

	// evaluates to false
	boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class);

	// evaluates to true
S
Sam Brannen 已提交
840
	String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";
841 842 843 844 845 846 847 848
	boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

	// -- OR --

	// evaluates to true
	boolean trueValue = parser.parseExpression("true or false").getValue(Boolean.class);

	// evaluates to true
S
Sam Brannen 已提交
849
	String expression = "isMember('Nikola Tesla') or isMember('Albert Einstein')";
850 851 852 853 854 855 856 857
	boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

	// -- NOT --

	// evaluates to false
	boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);

	// -- AND and NOT --
S
Sam Brannen 已提交
858
	String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
	boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
----


[[expressions-operators-mathematical]]
==== Mathematical operators
The addition operator can be used on both numbers and strings. Subtraction, multiplication
and division can be used only on numbers. Other mathematical operators supported are
modulus (%) and exponential power (^). Standard operator precedence is enforced. These
operators are demonstrated below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// Addition
	int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2

	String testString = parser.parseExpression(
S
Sam Brannen 已提交
877
			"'test' + ' ' + 'string'").getValue(String.class); // 'test string'
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

	// Subtraction
	int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4

	double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class); // -9000

	// Multiplication
	int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6

	double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); // 24.0

	// Division
	int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2

	double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class); // 1.0

	// Modulus
	int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3

	int one = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1

	// Operator precedence
	int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21
----



[[expressions-assignment]]
=== Assignment
Setting of a property is done by using the assignment operator. This would typically be
done within a call to `setValue` but can also be done inside a call to `getValue`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Inventor inventor = new Inventor();
	StandardEvaluationContext inventorContext = new StandardEvaluationContext(inventor);

	parser.parseExpression("Name").setValue(inventorContext, "Alexander Seovic2");

	// alternatively

	String aleks = parser.parseExpression(
S
Sam Brannen 已提交
921
			"Name = 'Alexandar Seovic'").getValue(inventorContext, String.class);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
----



[[expressions-types]]
=== Types
The special `T` operator can be used to specify an instance of java.lang.Class (the
_type_). Static methods are invoked using this operator as well. The
`StandardEvaluationContext` uses a `TypeLocator` to find types and the
`StandardTypeLocator` (which can be replaced) is built with an understanding of the
java.lang package. This means T() references to types within java.lang do not need to be
fully qualified, but all other type references must be.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);

	Class stringClass = parser.parseExpression("T(String)").getValue(Class.class);

	boolean trueValue = parser.parseExpression(
			"T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR")
			.getValue(Boolean.class);
----



[[expressions-constructors]]
=== Constructors
Constructors can be invoked using the new operator. The fully qualified class name
should be used for all but the primitive type and String (where int, float, etc, can be
used).

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Inventor einstein = p.parseExpression(
S
Sam Brannen 已提交
959
			"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
960 961 962 963 964
			.getValue(Inventor.class);

	//create new inventor instance within add method of List
	p.parseExpression(
			"Members.add(new org.spring.samples.spel.inventor.Inventor(
S
Sam Brannen 已提交
965
				'Albert Einstein', 'German'))").getValue(societyContext);
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
----



[[expressions-ref-variables]]
=== Variables
Variables can be referenced in the expression using the syntax `#variableName`. Variables
are set using the method setVariable on the `StandardEvaluationContext`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
	StandardEvaluationContext context = new StandardEvaluationContext(tesla);
	context.setVariable("newName", "Mike Tesla");

	parser.parseExpression("Name = #newName").getValue(context);

	System.out.println(tesla.getName()) // "Mike Tesla"
----


[[expressions-this-root]]
==== The #this and #root variables
The variable #this is always defined and refers to the current evaluation object
(against which unqualified references are resolved). The variable #root is always
defined and refers to the root context object. Although #this may vary as components of
an expression are evaluated, #root always refers to the root.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// create an array of integers
	List<Integer> primes = new ArrayList<Integer>();
	primes.addAll(Arrays.asList(2,3,5,7,11,13,17));

	// create parser and set variable 'primes' as the array of integers
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("primes",primes);

	// all prime numbers > 10 from the list (using selection ?{...})
	// evaluates to [11, 13, 17]
	List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression(
			"#primes.?[#this>10]").getValue(context);
----



[[expressions-ref-functions]]
=== Functions
You can extend SpEL by registering user defined functions that can be called within the
expression string. The function is registered with the `StandardEvaluationContext` using
the method.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public void registerFunction(String name, Method m)
----

A reference to a Java Method provides the implementation of the function. For example, a
utility method to reverse a string is shown below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public abstract class StringUtils {

		public static String reverseString(String input) {
			StringBuilder backwards = new StringBuilder();
			for (int i = 0; i < input.length(); i++)
				backwards.append(input.charAt(input.length() - 1 - i));
			}
			return backwards.toString();
		}
	}
----

This method is then registered with the evaluation context and can be used within an
expression string.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();

	context.registerFunction("reverseString",
		StringUtils.class.getDeclaredMethod("reverseString", new Class[] { String.class }));

	String helloWorldReversed = parser.parseExpression(
S
Sam Brannen 已提交
1058
		"#reverseString('hello')").getValue(context, String.class);
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
----



[[expressions-bean-references]]
=== Bean references
If the evaluation context has been configured with a bean resolver it is possible to
lookup beans from an expression using the (@) symbol.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new MyBeanResolver());

	// This will end up calling resolve(context,"foo") on MyBeanResolver during evaluation
	Object bean = parser.parseExpression("@foo").getValue(context);
----

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
To access a factory bean itself, the bean name should instead be prefixed with a (&) symbol.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new MyBeanResolver());

	// This will end up calling resolve(context,"&foo") on MyBeanResolver during evaluation
	Object bean = parser.parseExpression("&foo").getValue(context);
----
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101


[[expressions-operator-ternary]]
=== Ternary Operator (If-Then-Else)
You can use the ternary operator for performing if-then-else conditional logic inside
the expression. A minimal example is:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	String falseString = parser.parseExpression(
S
Sam Brannen 已提交
1102
			"false ? 'trueExp' : 'falseExp'").getValue(String.class);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
----

In this case, the boolean false results in returning the string value 'falseExp'. A more
realistic example is shown below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	parser.parseExpression("Name").setValue(societyContext, "IEEE");
	societyContext.setVariable("queryName", "Nikola Tesla");

S
Sam Brannen 已提交
1114 1115
	expression = "isMember(#queryName)? #queryName + ' is a member of the ' " +
			"+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

	String queryResultString = parser.parseExpression(expression)
			.getValue(societyContext, String.class);
	// queryResultString = "Nikola Tesla is a member of the IEEE Society"
----

Also see the next section on the Elvis operator for an even shorter syntax for the
ternary operator.



[[expressions-operator-elvis]]
=== The Elvis Operator
The Elvis operator is a shortening of the ternary operator syntax and is used in the
1130
http://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language.
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
With the ternary operator syntax you usually have to repeat a variable twice, for
example:

[source,groovy,indent=0]
[subs="verbatim,quotes"]
----
	String name = "Elvis Presley";
	String displayName = name != null ? name : "Unknown";
----

Instead you can use the Elvis operator, named for the resemblance to Elvis' hair style.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

E
Eric Bottard 已提交
1148
	String name = parser.parseExpression("name?:'Unknown'").getValue(String.class);
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

	System.out.println(name); // 'Unknown'
----

Here is a more complex example.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
	StandardEvaluationContext context = new StandardEvaluationContext(tesla);

S
Sam Brannen 已提交
1163
	String name = parser.parseExpression("Name?:'Elvis Presley'").getValue(context, String.class);
1164 1165 1166 1167 1168

	System.out.println(name); // Nikola Tesla

	tesla.setName(null);

S
Sam Brannen 已提交
1169
	name = parser.parseExpression("Name?:'Elvis Presley'").getValue(context, String.class);
1170 1171 1172 1173 1174 1175 1176 1177 1178

	System.out.println(name); // Elvis Presley
----



[[expressions-operator-safe-navigation]]
=== Safe Navigation operator
The Safe Navigation operator is used to avoid a `NullPointerException` and comes from
1179
the http://www.groovy-lang.org/operators.html#_safe_navigation_operator[Groovy]
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
language. Typically when you have a reference to an object you might need to verify that
it is not null before accessing methods or properties of the object. To avoid this, the
safe navigation operator will simply return null instead of throwing an exception.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	ExpressionParser parser = new SpelExpressionParser();

	Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
	tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));

	StandardEvaluationContext context = new StandardEvaluationContext(tesla);

	String city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);
	System.out.println(city); // Smiljan

	tesla.setPlaceOfBirth(null);

	city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);

	System.out.println(city); // null - does not throw NullPointerException!!!
----

[NOTE]
S
Stephane Nicoll 已提交
1205
====
1206 1207 1208 1209 1210 1211
The Elvis operator can be used to apply default values in expressions, e.g. in an
`@Value` expression:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
S
Sam Brannen 已提交
1212
	@Value("#{systemProperties['pop3.port'] ?: 25}")
1213 1214 1215
----

This will inject a system property `pop3.port` if it is defined or 25 if not.
S
Stephane Nicoll 已提交
1216
====
1217 1218 1219 1220 1221 1222 1223 1224



[[expressions-collection-selection]]
=== Collection Selection
Selection is a powerful expression language feature that allows you to transform some
source collection into another by selecting from its entries.

S
Stephane Nicoll 已提交
1225
Selection uses the syntax `.?[selectionExpression]`. This will filter the collection and
1226 1227 1228 1229 1230 1231 1232
return a new collection containing a subset of the original elements. For example,
selection would allow us to easily get a list of Serbian inventors:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	List<Inventor> list = (List<Inventor>) parser.parseExpression(
S
Sam Brannen 已提交
1233
			"Members.?[Nationality == 'Serbian']").getValue(societyContext);
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
----

Selection is possible upon both lists and maps. In the former case the selection
criteria is evaluated against each individual list element whilst against a map the
selection criteria is evaluated against each map entry (objects of the Java type
`Map.Entry`). Map entries have their key and value accessible as properties for use in
the selection.

This expression will return a new map consisting of those elements of the original map
where the entry value is less than 27.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Map newMap = parser.parseExpression("map.?[value<27]").getValue();
----

In addition to returning all the selected elements, it is possible to retrieve just the
first or the last value. To obtain the first entry matching the selection the syntax is
`^[...]` whilst to obtain the last matching selection the syntax is `$[...]`.



[[expressions-collection-projection]]
=== Collection Projection
Projection allows a collection to drive the evaluation of a sub-expression and the
result is a new collection. The syntax for projection is `![projectionExpression]`. Most
easily understood by example, suppose we have a list of inventors but want the list of
cities where they were born. Effectively we want to evaluate 'placeOfBirth.city' for
every entry in the inventor list. Using projection:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// returns ['Smiljan', 'Idvor' ]
	List placesOfBirth = (List)parser.parseExpression("Members.![placeOfBirth.city]");
----

A map can also be used to drive projection and in this case the projection expression is
evaluated against each entry in the map (represented as a Java `Map.Entry`). The result
of a projection across a map is a list consisting of the evaluation of the projection
expression against each map entry.



[[expressions-templating]]
=== Expression templating
Expression templates allow a mixing of literal text with one or more evaluation blocks.
Each evaluation block is delimited with prefix and suffix characters that you can
define, a common choice is to use `#{ }` as the delimiters. For example,

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	String randomPhrase = parser.parseExpression(
			"random number is #{T(java.lang.Math).random()}",
			new TemplateParserContext()).getValue(String.class);

	// evaluates to "random number is 0.7038186818312008"
----

The string is evaluated by concatenating the literal text 'random number is ' with the
result of evaluating the expression inside the #{ } delimiter, in this case the result
of calling that random() method. The second argument to the method `parseExpression()`
is of the type `ParserContext`. The `ParserContext` interface is used to influence how
the expression is parsed in order to support the expression templating functionality.
The definition of `TemplateParserContext` is shown below.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public class TemplateParserContext implements ParserContext {

		public String getExpressionPrefix() {
			return "#{";
		}

		public String getExpressionSuffix() {
			return "}";
		}

		public boolean isTemplate() {
			return true;
		}
	}
----




[[expressions-example-classes]]
== Classes used in the examples
Inventor.java

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package org.spring.samples.spel.inventor;

	import java.util.Date;
	import java.util.GregorianCalendar;

	public class Inventor {

		private String name;
		private String nationality;
		private String[] inventions;
		private Date birthdate;
		private PlaceOfBirth placeOfBirth;

		public Inventor(String name, String nationality) {
			GregorianCalendar c= new GregorianCalendar();
			this.name = name;
			this.nationality = nationality;
			this.birthdate = c.getTime();
		}

		public Inventor(String name, Date birthdate, String nationality) {
			this.name = name;
			this.nationality = nationality;
			this.birthdate = birthdate;
		}

		public Inventor() {
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getNationality() {
			return nationality;
		}

		public void setNationality(String nationality) {
			this.nationality = nationality;
		}

		public Date getBirthdate() {
			return birthdate;
		}

		public void setBirthdate(Date birthdate) {
			this.birthdate = birthdate;
		}

		public PlaceOfBirth getPlaceOfBirth() {
			return placeOfBirth;
		}

		public void setPlaceOfBirth(PlaceOfBirth placeOfBirth) {
			this.placeOfBirth = placeOfBirth;
		}

		public void setInventions(String[] inventions) {
			this.inventions = inventions;
		}

		public String[] getInventions() {
			return inventions;
		}
	}
----

PlaceOfBirth.java

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package org.spring.samples.spel.inventor;

	public class PlaceOfBirth {

		private String city;
		private String country;

		public PlaceOfBirth(String city) {
			this.city=city;
		}

		public PlaceOfBirth(String city, String country) {
			this(city);
			this.country = country;
		}

		public String getCity() {
			return city;
		}

		public void setCity(String s) {
			this.city = s;
		}

		public String getCountry() {
			return country;
		}

		public void setCountry(String country) {
			this.country = country;
		}

	}
----

Society.java

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package org.spring.samples.spel.inventor;

	import java.util.*;

	public class Society {

		private String name;

		public static String Advisors = "advisors";
		public static String President = "president";

		private List<Inventor> members = new ArrayList<Inventor>();
		private Map officers = new HashMap();

		public List getMembers() {
			return members;
		}

		public Map getOfficers() {
			return officers;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public boolean isMember(String name) {
			for (Inventor inventor : members) {
				if (inventor.getName().equals(name)) {
					return true;
				}
			}
			return false;
		}

	}
----