String expression1 = "#regParseInt('3') == #parseInt2('3')";
boolean result =
parser.parseExpression(expression1).getValue(context, boolean.class);
System.out.println("result="+result);
可以看出“registerFunction”和“setVariable”都可以注册自定义函数,但是两个方法的含义不一样,推荐使用“registerFunction”方法注册自定义函数。
赋值表达式
SpEL即允许给自定义变量赋值,也允许给跟对象赋值,直接使用“#variableName=value”即可赋值。示例如下:
java代码:
查看复制到剪贴板打印
1:parser.parseExpression("#root=‘Hi'").getValue(context, String.class);
2:parser.parseExpression("#this=‘Hi'").getValue(context, String.class);
3:context.setVariable("#variable", "variable");
对象属性存取及安全导航表达式
对象属性获取非常简单,使用如“a.property.property”这种点缀式获取,SpEL对于属性名首字母是不区分大小写的;
SpEL还引入了Groovy语言中的安全导航运算符“(对象|属性) .属性”,用来避免当“ .”前边的表达式为null时抛出空指针异常,而是返回null;
修改属性值可以通过赋值表达式或Expression接口的setValue方法修改。
示例如下:
java代码:
查看复制到剪贴板打印
UserModel um = new UserModel();
um.setUuid("User1");
um.setName("UserName1");
ExpressionParser parser = new SpelExpressionParser();
Standardeva luationContext context = new Standardeva luationContext();
context.setVariable("um",um);
//取值
Expression expression = parser.parseExpression("'uuid='+#um.uuid + ',name='+#um.name");
String v = expression.getValue(context,String.class);
System.out.println("v=="+v);
//赋值
expression = parser.parseExpression("'uuid='+(#um.uuid='newUser') + ',name='+#um.name");
v = expression.getValue(context,String.class);
System.out.println("v2=="+v);
输出结果:
v==uuid=User1,name=UserName1
v2==uuid=newUser,name=UserName1
对象方法调用
Bean引用
SpEL支持使用“@”符号来引用Bean,在引用Bean时需要使用BeanResolver接口实现来查找Bean,Spring提供BeanFactoryResolver实现,示例如下:
java代码:
查看复制到剪贴板打印
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml"});
ExpressionParser parser = new SpelExpressionParser();
Standardeva luationContext context = new Standardeva luationContext();
context.setBeanResolver(new BeanFactoryResolver(ctx));
String result1 =
parser.parseExpression("@myBean.test()").getValue(context, String.class);
内联List
从Spring3.0.4开始支持内联List,使用{表达式,……}定义内联List,如“{1,2,3}”将返回一个整型的ArrayList,而“{}”将返回空的List,对于字面量表达式列表,SpEL会使用java.util.Collections.unmodifiableList方法将列表设置为不可修改。示例如下:
1://将返回不可修改的空List
List
2:对于字面量列表也将返回不可修改的List
ExpressionParser parser = new SpelExpressionParser();
List
//result1.set(0, 2);//这句话会报错,因为list不可以修改
System. out.println(result1);
3://对于列表中只要有一个不是字面量表达式,将只返回原始List,
//不会进行不可修改处理,也就是可以修改
String expression3 = "{{1+2,2+4},{3,4+4}}";
List> result3 = parser.parseExpression(expression3).getValue(List.class);
result3.get(0).set(0, 1);
内联数组
和Java 数组定义类似,只是在定义时进行多维数组初始化。 示例如下:
1://定义一维数组并初始化
int[] result1 = parser.parseExpression("new int[1]").getValue(int[].class);
2://声明二维数组并初始化
int[] result2 = parser.parseExpression("new int[2]{1,2}").getValue(int[].class);
3://定义多维数组但不初始化
int[][][] result3 = parser.parseExpression(expression3).getValue(int[][][].class);
4://错误的定义多维数组,多维数组不能初始化
String expression4 = "new int[1][2][3]{{1}{2}{3}}";
int[][][] result4 = parser.pars