共计 1152 个字符,预计需要花费 3 分钟才能阅读完成。
MVEL 自定义表达式反复掉用报错:duplicate function
起因:第一次调用时会将 function 缓存,再次调用时提醒函数反复
计划:先将 funciton 放入缓存,再次调用时间接调用申明缓存中的函数
- 自定义函数名,不要与参数名雷同
示例代码:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MvelTest {
@Test
public void evalTest(){
// 表达式
String roundup = "def roundup(num) {roundnum = null; if(num != null){int roundnum = Math.round(num); } return roundnum; }";
VariableResolverFactory functionFactory = new MapVariableResolverFactory();
MVEL.eval(roundup, functionFactory);
VariableResolverFactory resolverFactory = new MapVariableResolverFactory();
resolverFactory.setNextFactory(functionFactory);
Map<String, Object> map = new HashMap<String, Object>();
map.put("A", new BigDecimal(2.33));
map.put("B", new BigDecimal(4));
String exp = "roundup(A*B)";
System.out.println(MVEL.eval(exp, map, resolverFactory));
System.out.println("------------");
VariableResolverFactory resolverFactory2 = new MapVariableResolverFactory();
resolverFactory2.setNextFactory(functionFactory);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("A", new BigDecimal(3.33));
map2.put("B", new BigDecimal(2));
System.out.println(MVEL.eval(exp, map2, resolverFactory2));
}
}
错误代码示例
向缓存中退出 roundup 函数
第一次执行胜利
再次调用再次向缓存中退出 roundup 函数
VariableResolverFactory 中存在函数抛出异样
正文完