手动执行Spring Expression Language评估时如何使用${key:default}属性引用
方案实现
仅调整SpEL配置实现 ${} 格式引用
第一步:自定义占位符规则
默认的TemplateParserContext使用#{作为前缀、}作为后缀,你可以自定义实例修改占位符格式为${}:
// 替换原有默认的TemplateParserContext实例 TemplateParserContext dollarParserContext = new TemplateParserContext("${", "}"); Expression expression = parser.parseExpression(htmlText, dollarParserContext);
第二步:简化属性引用写法
根据你的使用场景选择对应处理方式:
- 如果你需要保留SpEL的复杂表达式能力(比如运算、方法调用等),且Map的key不含特殊字符:
给上下文添加MapAccessor即可直接用${keyName}的格式引用,不需要加['']:String htmlText = IOUtils.toString(MailService.class.getResourceAsStream(resourceName),Charset.defaultCharset()); ExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(htmlText, new TemplateParserContext("${", "}")); StandardEvaluationContext context = new StandardEvaluationContext(); context.addPropertyAccessor(new MapAccessor()); // 新增Map属性访问器 if(contextMap != null) { context.setRootObject(contextMap); } String result = expression.getValue(context,String.class); return result; - 如果你只是做简单的占位符替换,不需要复杂表达式,更推荐用Spring原生的
PropertyPlaceholderHelper实现,完全匹配Spring属性文件的占位符规则,原生支持带点的key(比如my.key),代码更轻量:String htmlText = IOUtils.toString(MailService.class.getResourceAsStream(resourceName), Charset.defaultCharset()); // 定义占位符规则为${} PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}"); // 直接从Map中按key取值替换 String result = helper.replacePlaceholders(htmlText, contextMap::get); return result;
内容的提问来源于stack exchange,提问作者The Shoe Shiner
相关产品推荐
相关产品推荐

