springspring-expression-languagespring-expression

To use expression language to get values


My expression is :#age*10 And I assigned a value of 15.6 to age The result of this is 156.0 In fact the final result I want to get is:156

I can do it in the code, but how to do it by modifying the expression.

thanks


Solution

  • You need to use Integer.class as shown below:

    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 Demo {
        public static void main(String[] args) {
            ExpressionParser parser = new SpelExpressionParser();
            StandardEvaluationContext context = new StandardEvaluationContext();
            Double age = 15.6;
            context.setVariable("age", age);
            Expression exp = parser.parseExpression("#age*10");
            int result = exp.getValue(context, Integer.class);
            System.out.println(result);
        }
    }
    

    Output:

    156