Spring expression language (spiel) multi variable expression execution example of custom fault trigger condition

Keywords: Java

In the Internet of things project, the user-defined fault trigger conditions need to be handled. Expressions may be various, which requires the use of spiel to handle the expressions entered by users. The online examples are the assignment of single variables, which has no significance for the actual business. My example here is an expression for the input of multiple variables. I hope it will be useful to novice students.

 

	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 {//This line of code is abnormal
			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);

		//The following two lines of code will report an exception. You can only get the expression string and cannot continue to execute the expression
		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);
	}

 

Posted by chreez on Sun, 15 Dec 2019 13:12:09 -0800