BizExecuteUtil.java
3.17 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.xly.config;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Objects;
/**
* 业务逻辑执行工具:EL表达式 + Groovy脚本
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class BizExecuteUtil {
/**
* EL表达式解析器
*/
private final ExpressionParser elParser = new SpelExpressionParser();
/**
* Groovy类加载器
*/
private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
/**
* 执行业务逻辑
* @param bizType 1=EL,2=Groovy
* @param bizContent 逻辑内容
* @param params JSON参数
* @return 执行结果
*/
public String execute(Integer bizType, String bizContent, Map<String, Object> params) {
if (Objects.isNull(bizType) || Objects.isNull(bizContent) || bizContent.isBlank()) {
throw new IllegalArgumentException("业务逻辑配置异常");
}
// EL表达式执行
if (1 == bizType) {
return executeEL(bizContent, params);
}
// Groovy脚本执行
else if (2 == bizType) {
return executeGroovy(bizContent, params);
}
else {
throw new IllegalArgumentException("不支持的业务逻辑类型:" + bizType);
}
}
/**
* 执行EL表达式
*/
private String executeEL(String elContent, Map<String, Object> params) {
try {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("params", params);
Expression expression = elParser.parseExpression(elContent);
return expression.getValue(context, String.class);
} catch (Exception e) {
log.error("EL表达式执行失败:{}", elContent, e);
throw new IllegalArgumentException("EL表达式执行失败:" + e.getMessage());
}
}
/**
* 执行Groovy脚本
*/
private String executeGroovy(String groovyContent, Map<String, Object> params) {
try {
// 构建Groovy脚本类
String scriptCode = "class DynamicScript { def execute(Map params) { " + groovyContent + " } }";
Class<?> groovyClass = groovyClassLoader.parseClass(scriptCode);
GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance();
// 执行脚本并返回结果
Object result = groovyObject.invokeMethod("execute", new Object[]{params});
return Objects.isNull(result) ? "执行成功" : result.toString();
} catch (Exception e) {
log.error("Groovy脚本执行失败:{}", groovyContent, e);
throw new IllegalArgumentException("Groovy脚本执行失败:" + e.getMessage());
}
}
}