【问题标题】:Map for spring expression languagespring 表达式语言的映射
【发布时间】:2017-05-14 18:48:25
【问题描述】:

我想使用 SpEL 来评估一些谓词。由于值/属性是动态的,因此我没有特定的 bean 类。因此,我们有一个 hashmap,其中(根据应用程序状态)键映射到不同的 POJO/bean,例如:

Person person = new Person();// a person instance
person.setAge(25) // e.g. property age

Map<String, Object> model = new HashMap<>();
model.put("person", person);    
// and others ... 

我们希望通过设置变量来为此使用评估上下文,例如:

String predicate = "person.age>21";
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariables(model);
Expression expression = expressionParser.parseExpression(predicate);
boolean result = expression.getValue(context, Boolean.class);

但这会引发异常:

SpelEvaluationException: EL1007E:(pos 0): 在 null 上找不到属性或字段“person”

有人给点建议吗?

【问题讨论】:

    标签: java spring spring-el


    【解决方案1】:

    由于setVariables()中使用了映射,所以需要#person.age &gt; 21,因为person是一个变量。

    或者您可以将地图设置为上下文的根对象。

    context.setRootObject(model);
    

    或者忘记上下文并将根对象传递给评估

    expression.getValue(model, Boolean.class);
    

    【讨论】:

    • # 做到了。没有上下文就不起作用(抛出“在'java.util.HashMap'类型的对象上找不到属性-可能不是公共的”异常)
    • 啊 - 对 - 您需要一个评估上下文,并将 MapAccessor 添加到其 propertyAccessors。
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 2015-06-14
    • 2015-12-31
    • 2020-11-13
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多