1、定义对象StandardEvaluationContext

ExpressionParser expressionParser = new SpelExpressionParser();
StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext (){
                @Override
                public Object lookupVariable(String name) {
                    // 如果变量不存在,则返回默认值 0
                    if(super.lookupVariable(name) == null){
                        //如果未传值,则自动补
                        BigDecimal value=iotDbService.getLatestValue("%s.%s.*".formatted("equip_dcs",companyCode),name.replace("var_",""));
                        if(value==null){
                            return 0;
                        }
                        return value;
                    }
                    return super.lookupVariable(name);
                }
            };

2、定义表达式的变量的值

standardEvaluationContext.setVariable("a",11.9);

3、开始计算表达式

expressionParser.parseExpression(expression.replaceAll(regx, "var_$1").replaceAll("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b", "#$1")).getValue(standardEvaluationContext,BigDecimal.class);
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐