【问题标题】:Get property programmatically and evaluate it with SPEL以编程方式获取属性并使用 SPEL 对其进行评估
【发布时间】:2021-09-13 08:51:31
【问题描述】:

我试图通过使用Environment 从属性文件中检索属性,然后使用SpelExpressionParser 评估表达式,以编程方式模仿@Value 注释。

这是一个代码sn-p:

@Service
@Slf4j
public class Test {
    private String dynamicSPELStr = "#{${test.spel.map}.default}";

    @Autowired
    private Environment environment;
    void testSPEL() {
        ExpressionParser parser = new SpelExpressionParser();
        log.info("[PARSER] {}", parser
                .parseExpression(environment.resolvePlaceholders(dynamicSPELStr))
                .getValue());
    }
}

属性为:test.spel.map={default: '5', key1: '10', key2: '20', key3: '40'}

但是我收到以下错误:

Expression [#{{default: '5', key1: '10', key2: '20', key3: '40'}.default}] @1: EL1043E: Unexpected token. Expected 'identifier' but was 'lcurly({)'

使用@Value 运行相同的表达式就可以了。

【问题讨论】:

    标签: java spring spring-boot properties-file spring-expression-language


    【解决方案1】:

    @Value 注释的 value 属性不是 SpEL 表达式。它支持使用${...}的占位符,它支持使用#{...}的SpEL表达式。

    只有#{} 之间的文本才是SpEL 表达式。因此,从dynamicSPELStr 字符串中删除#{}

    private String dynamicSPELStr = "${test.spel.map}.default";
    

    错误说明

    SpEL 表达式使用#variableName 来访问变量(参见SpEL documentation4.3.10. Variables 部分)。

    由于dynamicSPELStr 的开头是#{,表达式解析器抱怨# 变量前缀后面没有有效的名称字符,因此错误 "Expected 'identifier' but是'lcurly({)'"

    【讨论】:

    • 非常感谢,现在更清楚了。现在我收到一个不同的错误:EL1008E: Property or field 'default' cannot be found on object of type 'java.util.Collections$UnmodifiableMap' - maybe not public or not valid? 。知道为什么会这样吗?
    • @MihaiCatalinValentin 不,但尝试['default'] 而不是.default
    猜你喜欢
    • 2020-12-03
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多