DynamicTextInjector.java
1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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<String, Object> 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<String, Object> params) {
String result = template;
// 替换 {{variable}} 格式
for (Map.Entry<String, Object> entry : params.entrySet()) {
String placeholder = "{{" + entry.getKey() + "}}";
result = result.replace(placeholder,
entry.getValue() != null ? entry.getValue().toString() : "");
}
// 替换 ${variable} 格式
for (Map.Entry<String, Object> entry : params.entrySet()) {
String placeholder = "${" + entry.getKey() + "}";
result = result.replace(placeholder,
entry.getValue() != null ? entry.getValue().toString() : "");
}
return result;
}
}