我需要使用Spring表达式语言计算基于bean的动态用户生成的表达式,但我希望通过注释限制它们可以使用的字段。例如,如果我有下面的类,我希望能够计算表达式field1 + field2,但是如果我尝试计算field1 + field3,这将导致生成异常。
这个是可能的吗?有没有不同的方法来限制表达式的范围?
public class Foo {
@AllowedField
private int field1;
@AllowedField
private int field2;
private int field3;
}发布于 2018-08-23 04:58:37
基本上,这就是你需要做的
扩展StandardEvaluationContext以返回您自己的PropertyAccessor
public class SecureEvaluationContext extends StandardEvaluationContext {
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return Arrays.asList(new SecurePropertyAccessor());
}
}扩展ReflectivePropertyAccessor并实现您自己的canRead
public class SecurePropertyAccessor extends ReflectivePropertyAccessor {
@Override
public boolean canRead(EvaluationContext context, Object target, String name) {
boolean canRead = // Add your own logic as needed
return canRead;
}
}通过以下方式评估:
Expression expression = parser.parseExpression("field1 + field2");
EvaluationContext evaluationContext = new SecureEvaluationContext();
Double value = expression.getValue(evaluationContext, new ControlElement(), Double.class);https://stackoverflow.com/questions/51737529
复制相似问题