前言
SpEL(Spring Expression Language),即Spring表达式语言,是比JSP的EL更强大的一种表达式语言。为什么要总结SpEL,因为它可以在运行时查询和操作数据,尤其是数组列表型数据,因此可以缩减代码量,优化代码结构。个人认为很有用。
一. 用法
SpEL有三种用法,一种是在注解@Value中;一种是XML配置;最后一种是在代码块中使用Expression。
- @Value
//@Value能修饰成员变量和方法形参 //#{}内就是表达式的内容 @Value("#{表达式}") public String arg;
- <bean>配置
<bean id="xxx" class="com.java.XXXXX.xx">
<!-- 同@Value,#{}内是表达式的值,可放在property或constructor-arg内 -->
<property name="arg" value="#{表达式}">
</bean>
- Expression
import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class SpELTest { public static void main(String[] args) { //创建ExpressionParser解析表达式 ExpressionParser parser = new SpelExpressionParser(); //表达式放置 Expression exp = parser.parseExpression("表达式"); //执行表达式,默认容器是spring本身的容器:ApplicationContext Object value = exp.getValue(); /**如果使用其他的容器,则用下面的方法*/ //创建一个虚拟的容器EvaluationContext StandardEvaluationContext ctx = new StandardEvaluationContext(); //向容器内添加bean BeanA beanA = new BeanA(); ctx.setVariable("bean_id", beanA); //setRootObject并非必须;一个EvaluationContext只能有一个RootObject,引用它的属性时,可以不加前缀 ctx.setRootObject(XXX); //getValue有参数ctx,从新的容器中根据SpEL表达式获取所需的值 Object value = exp.getValue(ctx); } }
二. 表达式语法
一、字面量赋值
<!-- 整数 --> <property name="count" value="#{5}" /> <!-- 小数 --> <property name="frequency" value="#{13.2}" /> <!-- 科学计数法 --> <property name="capacity" value="#{1e4}" /> <!-- 字符串 #{"字符串"} 或 #{'字符串'} --> <property name="name" value="#{'我是字符串'}" /> <!-- Boolean --> <property name="enabled" value="#{false}" />
注: 1)字面量赋值必须要和对应的属性类型兼容,否则会报异常。
2)一般情况下我们不会使用 SpEL字面量赋值,因为我们可以直接赋值。
2.引用Bean、属性和方法(必须是public修饰的)
<property name="car" value="#{car}" /> <!-- 引用其他对象的属性 --> <property name="carName" value="#{car.name}" /> <!-- 引用其他对象的方法 --> <property name="carPrint" value="#{car.print()}" />
3.运算符
3.1
算术运算符:+,-,*,/,%,^
<!-- 3 --> <property name="num" value="#{2+1}" /> <!-- 1 --> <property name="num" value="#{2-1}" /> <!-- 4 --> <property name="num" value="#{2*2}" /> <!-- 3 --> <property name="num" value="#{9/3}" /> <!-- 1 --> <property name="num" value="#{10%3}" /> <!-- 1000 --> <property name="num" value="#{10^3}" />
3.2
字符串连接符:+
<!-- 10年3个月 --> <property name="numStr" value="#{10+'年'+3+'个月'}" />
3.3
比较运算符:<(<),>(>),==,<=,>=,lt,gt,eq,le,ge
<!-- false --> <property name="numBool" value="#{10<0}" /> <!-- false --> <property name="numBool" value="#{10 lt 0}" /> <!-- true --> <property name="numBool" value="#{10>0}" /> <!-- true --> <property name="numBool" value="#{10 gt 0}" /> <!-- true --> <property name="numBool" value="#{10==10}" /> <!-- true --> <property name="numBool" value="#{10 eq 10}" /> <!-- false --> <property name="numBool" value="#{10<=0}" /> <!-- false --> <property name="numBool" value="#{10 le 0}" /> <!-- true --> <property name="numBool" value="#{10>=0}" /> <!-- true --> <property name="numBool" value="#{10 ge 0}" />
3.4
逻辑运算符:and,or,not,&&(&&),||,!
<!-- false --> <property name="numBool" value="#{10<0}" /> <!-- false --> <property name="numBool" value="#{10 lt 0}" /> <!-- true --> <property name="numBool" value="#{10>0}" /> <!-- true --> <property name="numBool" value="#{10 gt 0}" /> <!-- true --> <property name="numBool" value="#{10==10}" /> <!-- true --> <property name="numBool" value="#{10 eq 10}" /> <!-- false --> <property name="numBool" value="#{10<=0}" /> <!-- false --> <property name="numBool" value="#{10 le 0}" /> <!-- true --> <property name="numBool" value="#{10>=0}" /> <!-- true --> <property name="numBool" value="#{10 ge 0}" />
3.5
条件运算符:?true:false
<!-- 真 --> <property name="numStr" value="#{(10>3)?'真':'假'}" />
3.6
正则表达式:matches
<!-- true --> <property name="numBool" value="#{user.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}'}" />
4调用静态方法或静态属性
通过 T() 调用一个类的静态方法,它将返回一个 Class Object,然后再调用相应的方法或属性:
<!-- true --> <property name="numBool" value="#{user.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}'}" />
-
获取容器内的变量,可以使用“#bean_id”来获取。有两个特殊的变量,可以直接使用。
this 使用当前正在计算的上下文
root 引用容器的root对象
String result2 = parser.parseExpression("#root").getValue(ctx, String.class); String s = new String("abcdef"); ctx.setVariable("abc",s); //取id为abc的bean,然后调用其中的substring方法 parser.parseExpression("#abc.substring(0,1)").getValue(ctx, String.class);
6.方法调用
与Java代码没有什么区别,可见上面的例子
可以自定义方法,如下:
Method parseInt = Integer.class.getDeclaredMethod("parseInt", String.class); ctx.registerFunction("parseInt", parseInt); ctx.setVariable("parseInt2", parseInt);
“registerFunction”和“setVariable”都可以注册自定义函数,但是两个方法的含义不一样,推荐使用“registerFunction”方法注册自定义函数。
7.Elvis运算符
是三目运算符的特殊写法,可以避免null报错的情况
name != null? name : "other" //简写为: name?:"other"
8.安全保证
为了避免操作对象本身可能为null,取属性时报错,定义语法
语法: “对象?.变量|方法”
name != null? name : "other" //简写为: name?:"other"
- 直接使用java代码new/instance of
此方法只能是java.lang 下的类才可以省略包名
Expression exp = parser.parseExpression("new Spring('Hello World')");
-
集合定义
使用“{表达式,……}”定义List,如“{1,2,3}”对于字面量表达式列表,SpEL会使用java.util.Collections.unmodifiableList 方法将列表设置为不可修改。
对于列表中只要有一个不是字面量表达式,将只返回原始List,
//不会进行不可修改处理,也就是可以修改
List<Integer> result1 = parser.parseExpression("{1,2,3}").getValue(List.class);
11.集合访问
SpEL目前支持所有集合类型和字典类型的元素访问 语法:“集合[索引]”、“map[key]”
EvaluationContext context = new StandardEvaluationContext();
//即list.get(0)
int result1 = parser.parseExpression("{1,2,3}[0]").getValue(int.class);
//list获取某一项
Collection<Integer> collection = new HashSet<Integer>();
collection.add(1);
collection.add(2);
context.setVariable("collection", collection);
int result2 = parser.parseExpression("#collection[1]").getValue(context, int.class);
//map获取
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
context.setVariable("map", map);
int result3 = parser.parseExpression("#map['a']").getValue(context, int.class);
12. 集合修改
可以使用赋值表达式或Expression接口的setValue方法修改;
//赋值语句
int result = parser.parseExpression("#array[1] = 3").getValue(context, int.class);
//serValue方法
parser.parseExpression("#array[2]").setValue(context, 4);
13. 集合选择 通过一定的规则对及格进行筛选,构造出另一个集合 语法:“(list|map).?[选择表达式]” 选择表达式结果必须是boolean类型,如果true则选择的元素将添加到新集合中,false将不添加到新集合中
parser.parseExpression("#collection.?[#this>2]").getValue(context, Collection.class);
上面的例子从数字的collection集合中选出数字大于2的值,重新组装成了一个新的集合 14. 上面的例子从数字的collection集合中选出数字大于2的值,重新组装成了一个新的集合 根据集合中的元素中通过选择来构造另一个集合,该集合和原集合具有相同数量的元素 语法:“SpEL使用“(list|map).![投影表达式]”
public class Book {
public String name; //书名 public String author; //作者 public String publisher; //出版社 public double price; //售价 public boolean favorite; //是否喜欢
}
public class BookList {
@Autowired
protected ArrayList<Book> list = new ArrayList<Book>() ; protected int num = 0;
}
将BookList的实例映射为bean:readList,在另一个bean中注入时,进行投影
//从readList的list下筛选出favorite为true的子集合,再将他们的name字段投为新的list @Value("#{list.?[favorite eq true].![name]}") private ArrayList<String> favoriteBookName;
- Bean引用:
SpEL支持使用“@”符号来引用Bean,在引用Bean时需要使用BeanResolver接口实现来查找Bean,Spring提供BeanFactoryResolver实现;
@Test public void testBeanExpression() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.refresh(); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new BeanFactoryResolver(ctx)); Properties result1 = parser.parseExpression("@systemProperties").getValue(context, Properties.class); Assert.assertEquals(System.getProperties(), result1); }
作者:阿杜_智能IVR
链接:https://www.jianshu.com/p/e0b50053b5d3
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。