我需要使用 Spring 表达式语言评估基于 bean 的动态用户生成表达式,但我希望限制它们可以通过注释使用的字段。例如,如果我有下面的类,我希望能够计算表达式 field1 + field2
,但如果我尝试计算 field1 + field3
这将导致正在生成异常。
这可能吗?有没有不同的方法来限制表达式的范围?
public class Foo {
@AllowedField
private int field1;
@AllowedField
private int field2;
private int field3;
}
最佳答案
基本上,这就是您需要做的
扩展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);
关于java - Spring 表达式语言 (SPEL) 限制对给定注释的 bean 字段的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51737529/