物联网项目中需要处理用户自定义的故障触发条件,表达式可能千奇百怪,这就需要用到SpEL来处理用户输入的表达式了,网上的例子都是单个变量的赋值,对于实际的业务没有任何意义。我这里的例子是多个变量的输入的表达式。希望对新手同学有用。
public void testAAA(){
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("A", "haha");
String result1 = parser.parseExpression("#A").getValue(context, String.class);//haha
String result2 = parser.parseExpression("{#A}").getValue(context, String.class);//haha
try {//此行代码异常
String result3 = parser.parseExpression("#{#V1}").getValue(context, String.class);
}
catch (Exception e) {
e.printStackTrace();//Unexpected token. Expected 'identifier' but was 'lcurly({)'
}
LOG.info("{},{}",result1,result2);
}
public void testBBB()
{
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evContext = new StandardEvaluationContext();
evContext.setVariable("A", 5);
evContext.setVariable("B", 2);
String expressionTemplate1 = "#{#A}+#{#B}< 2";
String expressionTemplate2 = "#{#A}+#{#B}> 2";
String result1 = parser.parseExpression(expressionTemplate1, new TemplateParserContext()).getValue(evContext,String.class);
String result2 = parser.parseExpression(expressionTemplate2, new TemplateParserContext()).getValue(evContext,String.class);
//下面这两行代码会报异常, 只能获取表达式字符串,没法继续执行表达式
try {
String result3 = parser.parseExpression(expressionTemplate1, new TemplateParserContext()).getValue(evContext,boolean.class).toString();
String result4 = parser.parseExpression(expressionTemplate2, new TemplateParserContext()).getValue(evContext,boolean.class).toString();
}
catch (Exception e) {
e.printStackTrace();//can not convert from java.lang.String to boolean
}
String value1 = parser.parseExpression(result1).getValue().toString();//false
String value2 = parser.parseExpression(result2).getValue().toString();//true
boolean value3 = parser.parseExpression(result1).getValue(boolean.class);//false
boolean value4 = parser.parseExpression(result2).getValue(boolean.class);//true
LOG.info("{},{}", result1,value1);
LOG.info("{},{}", result2,value2);
}