java - Spring 表达式语言 (SPEL) 限制对给定注释的 bean 字段的访问

标签 java spring spring-el

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

相关文章:

java - JFreeChart 条形图自定义颜色?

mysql - 使用 flyway 时在启动时清除数据库

java - 如何访问 JavaScript 文件中的 Spring MVC 模型对象?

Spring 启动 : Multiple similar ConfigurationProperties with different Prefixes

java - Spring组件扫描中的表达式

java - 为什么我的 String 对象没有被设置为索引 0 处的命令行参数?

java - NoClassDefFoundError : com/mysql/jdbc/StringUtils Tomcat 6

java - Netbeans 的 Hibernate Unicode;为什么在db中保存为 "?????"

xml - 在 xpath 中连接多个节点值

java - Hazelcast 查询可以使用对象方法吗?