SpEL语法

SpEL即Spring Expression Language,是一种功能强大的表述语言

SpEL具有的特性

1 文字表达
2 关系和逻辑表达
3 正则表达式
4 类
5 可以访问属性,数组,lists,maps
6 方法调用
7 赋值(Assignment)
8 调用构造函数
9 Bean references
10 内联的集合
11 三元操作
12 变量
13 集合注入
14 集合选择

SpEL的api在org.springframework.expression包里面,下面是API的例子

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'");
String message = (String) exp.getValue();

详细的用法

SpEL可以调用方法
"'Hello World'.concat('!')"

SpEL可以访问它的属性
"'Hello World'.bytes"

SpEL支持嵌套访问属性
"'Hello World'.bytes.length"

SpEL可以调有构造函数
"new String('hello world').toUpperCase()"

SpEL可以调用当前对象的某个属性,直接用属性名
"name"

SpEL运用逻辑表达式
"name == 'Nikola Tesla'" //判断当前对象的name是否为'Nikola Tesla'

SpEL取某个对象的booleanList属性的第一个元素,booleanList是个集合
"booleanList[0]"

在XML中写SpEL表达式
"#{ }"
<property name="defaultLocale" value="#{ systemProperties['user.region'] }"/> //user.region必须是预先定义好的
value="#{ numberGuess.randomNumber }" //numberGuess是某个bean的name,randomNumber是那个bean的属性name

基于Annotation的配置
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;

另一种写法
@Value("#{ systemProperties['user.region'] }")
public void setDefaultLocale(String defaultLocale)
{
this.defaultLocale = defaultLocale;
}

放到参数列表里
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.region'] }"} String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}


map的用法
"Officers['president']"
"Officers['president'].PlaceOfBirth.City"
"Officers['advisors'][0].PlaceOfBirth.Country"

内联的集合
"{1,2,3,4}"
"{{'a','b'},{'x','y'}}"

数组构造
"new int[4]"
"new int[]{1,2,3}"
"new int[4][5]"
目前不支持多维数组的初始化

方法调用
"isMember('Mihajlo Pupin')"

逻辑运算
"2 < -5.0"

支持instanceof
"'xyz' instanceof T(int)"

正则表达式
"'5.00' matches '^-?\\d+(\\.\\d{2})?$'"

支持and,or,not

支持四则运算,取模

可以使用赋值语句
"Name = 'Alexandar Seovic'"

可以得到一个类,并调用它的静态方法,除了java.lang包下,其它的要加完整
"T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR"的包名

访问构造函数
"new org.spring.samples.spel.inventor.Inventor('Albert Einstein',
'German')"

引用变量
"Name = #newName"

#this指当前的表达式#root指当前对象

@bean-name引用bean

三元运算符
"false ? 'trueExp' : 'falseExp'"

保险用法
@Value("#{systemProperties['pop3.port'] ?: 25}") //如果为空就是默认25

集合筛选
"Members.?[Nationality == 'Serbian']"
"map.?[value<27]"

原文地址:https://www.cnblogs.com/angelshelter/p/2735723.html