簡體   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