package com.xly.util; import org.springframework.expression.ExpressionParser; import org.springframework.expression.common.TemplateParserContext; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import java.util.Map; /** * 动态文本注入工具类 */ public class DynamicTextInjector { /** * 使用Spring EL表达式注入 */ public static String injectWithSpEL(String template, Map variables) { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); // 设置变量 variables.forEach(context::setVariable); // 解析模板 return parser.parseExpression(template, new TemplateParserContext()).getValue(context, String.class); } /** * 自定义模板解析 */ public static String injectCustom(String template, Map params) { String result = template; // 替换 {{variable}} 格式 for (Map.Entry entry : params.entrySet()) { String placeholder = "{{" + entry.getKey() + "}}"; result = result.replace(placeholder, entry.getValue() != null ? entry.getValue().toString() : ""); } // 替换 ${variable} 格式 for (Map.Entry entry : params.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; result = result.replace(placeholder, entry.getValue() != null ? entry.getValue().toString() : ""); } return result; } }