繁体   English   中英

Spring Expression Language(SPEL)限制对具有给定注释的Bean字段的访问

[英]Spring Expression Language (SPEL) limit access to bean fields with a given annotation

我需要使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM