【问题标题】:SpEL expressions - identify fields declared in an expression?SpEL 表达式 - 识别表达式中声明的字段?
【发布时间】:2014-11-14 11:49:53
【问题描述】:

我有以下代码,它使用 Map 对象中定义的数据值评估 SpEL 表达式。

// data map
Map dataMap = new HashMap();
dataMap.put("abc",1);
dataMap.put("def",2);
dataMap.put("xyz",1);
dataMap.put("qwerty",2);

// spel rule expression
String ruleExpression = "#abc+#def";

// Set evaluation context
StandardEvaluationContext stdContext = new StandardEvaluationContext();
stdContext.setVariables(map);

// Evaluate the SpEL expression
ExpressionParser parser = new SpelExpressionParser();
Object returnValue = parser.parseExpression(ruleExpression).getValue(stdContext);

// returnValue = 3 :-)

在现实世界中,我们的地图是根据数据库查询结果集填充的,并且“ruleExpression”仅在运行时才知道。我有一个新要求来记录“ruleExpression”中定义的值,以便生成这样的字符串

abc=1,def=2

一种蛮力方法可能会让我们使用正则表达式解析“ruleExpression”字符串以识别以“#”开头的字段名,但我可以看到随着 ruleExpression 复杂性的增加,这可能会变得混乱。

我想知道,由于 SpEl 引擎必须在 parseExpress() 阶段识别在“ruleExpression”中声明的字段,有没有办法让我们重用这个逻辑?

编辑 - 我确实在 org.springframework.expression.spel.ExpressionState 类上遇到了 VariableScope 私有内部类,它似乎可以满足我的要求,但可惜它无法访问。

【问题讨论】:

    标签: regex spring spring-el


    【解决方案1】:

    您可以尝试在StandardExpressionContext 中覆盖lookupVariable 并在那里添加您的登录。将 stdContext 替换为以下内容将捕获每个使用的变量:

        StandardEvaluationContext stdContext = new StandardEvaluationContext() {
            @Override
            public Object lookupVariable(String name) {
                Object value = super.lookupVariable(name);
                //do logging here
                System.out.println(name + "=" + value);
                return value;
            }
        };
    

    这个输出:

    abc=1
    def=2
    

    这只会捕获变量中使用的值。任何来自 bean 或其他对象等的东西都不会通过lookupVariable。从未使用过的变量值也不会(例如由于条件)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多