从 Spring 表达式中修改 rootObject

Modify rootObject from within a Spring expression

是否可以使用 SpEL 从表达式中修改提供的 rootObject

考虑以下代码以了解我的意思:

波乔:

public class Person {

    private int     age;
    private boolean mature;

    // getters and setters omitted for brevity
}

表达式:

Person person = new Person();
person.setAge(18);

SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader());
ExpressionParser parser = new SpelExpressionParser(config);
Expression ex = parser.parseExpression("age >= 18");
boolean result = ex.getValue(person, Boolean.class);

看看下面我想做什么。这可能吗?

ex = parser.parseExpression("if (age >= 18) {mature = true}");
// person now has mature == true

编辑:

可以使用 javax.script 而不是 SpEL,它支持 JavaScript 并包含在 JVM 中。这里有一个例子:

ScriptEngineManager manager = new ScriptEngineManager(); 
ScriptEngine jsEngine = manager.getEngineByName("JavaScript");

Person person = new Person();
person.setAge(18);

jsEngine.put("person", person);

jsEngine.eval("if (person.getAge() >= 18) { person.setMature(true); }");

// Calling person.isMature() in Java will now return `true`.

不,您会收到下一个异常 SpelParseException,下一条消息错误 After parsing a valid expression, there is still more data in the expression

您可以按照以下两个选项进行操作:

使用三元运算符:

SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader());
ExpressionParser parser = new SpelExpressionParser(config);

Boolean parsedValue = parser.parseExpression("age >= 18 ? Mature=true : Mature=false").getValue(person, Boolean.class);

System.out.println(person.getMature()); // Output = true
System.out.println(parsedValue); //Output = true

有两个 spEL 表达式:

SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader());
ExpressionParser parser = new SpelExpressionParser(config);
Expression ex = parser.parseExpression("age >= 18");
boolean result = ex.getValue(person, Boolean.class);

if(result)
   parser.parseExpression("mature").setValue(person, "true");

System.out.println(person.getMature()); //Output = true