Spring 表达式语言 (SPEL) 限制对具有给定注释的 bean 字段的访问
Spring Expression Language (SPEL) limit access to bean fields with a given annotation
我需要使用 Spring 表达式语言评估基于 bean 的动态用户生成表达式,但我希望通过注释限制它们可以使用的字段。例如,如果我有下面的 class,我希望能够计算表达式 field1 + field2
,但是如果我尝试计算 field1 + field3
,这将导致生成异常。
这可能吗?是否有不同的方式来限制表达式的范围?
public class Foo {
@AllowedField
private int field1;
@AllowedField
private int field2;
private int field3;
}
基本上,这就是您需要做的
扩展StandardEvaluationContext
到return你自己的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);
我需要使用 Spring 表达式语言评估基于 bean 的动态用户生成表达式,但我希望通过注释限制它们可以使用的字段。例如,如果我有下面的 class,我希望能够计算表达式 field1 + field2
,但是如果我尝试计算 field1 + field3
,这将导致生成异常。
这可能吗?是否有不同的方式来限制表达式的范围?
public class Foo {
@AllowedField
private int field1;
@AllowedField
private int field2;
private int field3;
}
基本上,这就是您需要做的
扩展StandardEvaluationContext
到return你自己的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);