spEL表达式
SpEL(Spring Expression Language)是一种表达式语言,是一种可以与一个基于spring的应用程序中的运行时对象交互的东西;一种简化开发的表达式,通过使用表达式来简化开发,减少一些逻辑、配置的编写。
-
用法
SpEL有三种用法,一种是在注解@Value中;一种是XML配置;最后一种是在代码块中使用Expression。
1、注解
@Value("#{表达式}")
public String name;
Spring容器中按照SpEL表达式筛选修改数据后,赋值给所修饰的变量
2、XML配置
<bean id="user" class="cn.spy.spel.method.User">
<property name="username" value="#{user.getUsername()}"></property>
<property name="password" value="#{user.getPassword()}"></property>
</bean>
与注解类似
3、代码中Expression
1、静态方法
public static void main(String[] args) {
//创建ExpressionParser解析表达式
ExpressionParser parser = new SpelExpressionParser();
//表达式放置
Expression exp = parser.parseExpression("1 > 2");
//执行表达式,默认容器是spring本身的容器:ApplicationContext
Object value = exp.getValue();
//输出false
System.out.println(value);
}
2、变量的表达式使用
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context =new StandardEvaluationContext();
context.setVariable("message", " 1 > 2 ");
String value =parser.parseExpression("#message").getValue(context, String.class);
//输出 1 > 2
System.out.println(value);
}
3、root表达式的使用
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context =new StandardEvaluationContext();
context.setRootObject("message");
Object value1 =parser.parseExpression("#root.substring(0,1)").getValue(context);
//输出m
System.out.println(value1);
}
4、SpEL表达式中的运算符
类型 | 运算符 | 举例 |
关系 | <,>,<=,>=,==,!=,lt,gt,le,ge,eq,ne | 1>2 |
条件 | ?: (ternary),?: (elvis) | name?:"other" |
逻辑 | &&,||,!,and,or,not,between,instanceof | 3 between {2,5} |
算术 | +,- ,* ,/,%,^ | 1+2 |
正则表达 | matches | “123′ matches ‘\\d{3}” |
其他类型 | ?.,?[…],![…],^[…],$[…] | list?.length |
5、集合操作
A、定义:List<Integer> result1 = parser.parseExpression("{1,2,3}").getValue(List.class);
B、访问:parser.parseExpression("#collection[1]").getValue(context); --list
parser.parseExpression("#map['a']").getValue(context); --map
C、修改:parser.parseExpression("#array[2]").setValue(context, 4);
D、赋值:parser.parseExpression("#array[1] = 3").getValue(context, int.class);
E、集合选择:语法:“(list|map).?[选择表达式]”
eg:parser.parseExpression("#collection.?[#this>2]").getValue(context, Collection.class);