对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

属性、数组、列表、映射和索引器

通过属性引用进行导航很容易。为此,请使用句点表示嵌套属性值。Inventor类、pupintesla的实例已填充了在示例中使用的类部分列出的数据。要“向下”遍历对象图并获取特斯拉的出生年份和普林的出生城市,我们使用以下表达式:spring-doc.cadn.net.cn

// evaluates to 1856
int year = (Integer) parser.parseExpression("birthdate.year + 1900").getValue(context);

String city = (String) parser.parseExpression("placeOfBirth.city").getValue(context);
// evaluates to 1856
val year = parser.parseExpression("birthdate.year + 1900").getValue(context) as Int

val city = parser.parseExpression("placeOfBirth.city").getValue(context) as String

属性名称的第一个字母不区分大小写。因此,上面示例中的表达式可以分别写成Birthdate.Year + 1900PlaceOfBirth.City。此外,还可以通过方法调用可选地访问属性 — 例如,使用getPlaceOfBirth().getCity()代替placeOfBirth.cityspring-doc.cadn.net.cn

数组和列表的内容通过使用方括号表示法获取,如下例所示:spring-doc.cadn.net.cn

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

// Inventions Array

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

// Members List

// evaluates to "Nikola Tesla"
String name = parser.parseExpression("members[0].name").getValue(
		context, ieee, String.class);

// List and Array navigation
// evaluates to "Wireless communication"
String invention = parser.parseExpression("members[0].inventions[6]").getValue(
		context, ieee, String.class);
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadOnlyDataBinding().build()

// Inventions Array

// evaluates to "Induction motor"
val invention = parser.parseExpression("inventions[3]").getValue(
		context, tesla, String::class.java)

// Members List

// evaluates to "Nikola Tesla"
val name = parser.parseExpression("members[0].name").getValue(
		context, ieee, String::class.java)

// List and Array navigation
// evaluates to "Wireless communication"
val invention = parser.parseExpression("members[0].inventions[6]").getValue(
		context, ieee, String::class.java)

映射的内容是通过在方括号内指定字面量键值来获取的。在下面的例子中,因为officers映射的键是字符串,我们可以指定字符串字面量:spring-doc.cadn.net.cn

// Officer's Dictionary

Inventor pupin = parser.parseExpression("officers['president']").getValue(
		societyContext, Inventor.class);

// evaluates to "Idvor"
String city = parser.parseExpression("officers['president'].placeOfBirth.city").getValue(
		societyContext, String.class);

// setting values
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
		societyContext, "Croatia");
// Officer's Dictionary

val pupin = parser.parseExpression("officers['president']").getValue(
		societyContext, Inventor::class.java)

// evaluates to "Idvor"
val city = parser.parseExpression("officers['president'].placeOfBirth.city").getValue(
		societyContext, String::class.java)

// setting values
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
		societyContext, "Croatia")