我正在处理表达式并尝试使用上下文(我们在创建时使用的上下文和我们在评估时使用的上下文)。下面是一些代码,试图重现我的需求并突出显示问题。
ExpressionFactory factory = new ExpressionFactoryImpl();
SimpleContext createContext = new SimpleContext();
createContext.setVariable("myBean", factory.createValueExpression(new MyBean("Laurent"), MyBean.class));
String expression;
expression = "${myBean.foo} ${exchange.host}";
ValueExpression expr = factory.createValueExpression(createContext, expression, String.class);
System.out.println("expr Class : " + expr.getClass());
SimpleContext evalContext = new SimpleContext();
List<String> hosts = asList("www.example.com", "www.foo.com", "www.bar.com");
// I want to evaluate the same expression, but with different values for the variable exchange.
for (String host : hosts) {
evalContext.setVariable("exchange", factory.createValueExpression(new MyExchange(host), MyExchange.class));
System.out.println(expression + " = " + expr.getValue(evalContext));
}
我在 https://github.com/laurentvaills/test-juel-expression 上设置了一个基本的Maven项目来重现它。
你能告诉我为什么我得到以下错误吗:javax.el.PropertyNotFoundException: Cannot find property exchange ?
这不是 JUEL 问题,而是一般的 EL 问题。变量在解析时绑定。表达式解析后,无法更改它们。在评估时,您需要改用属性:
evalContext.getELResolver().setValue(
evalContext,
null,
"exchange",
new MyExchange(host));
有关详细信息,请参阅 ELResolver 的文档。