依赖
查询依赖与版本号: https://search.maven.org/
<dependency>
<groupId>org.apache.groovy</groupId>
<artifactId>groovy</artifactId>
<version>4.0.3</version>
</dependency>
执行脚本
1. 代码块
执行 shell 脚本,非类的方式
public Object method(String rule, Map<String, Object> params) {
Binding binding = new Binding(params);
GroovyShell shell = new GroovyShell(binding);
try {
return shell.evaluate(rule);
}finally {
shell.getClassLoader().clearCache();
}
}
2. 类
对一个类进行 groovy 脚本的执行
public Object method(String rule, Map<String, Object> params) {
try {
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
//将Groovy脚本解析为Class对象
Class<?> clazz = groovyClassLoader.parseClass(rule);
if (clazz != null) {
GroovyObject groovyObject = (GroovyObject) clazz.newInstance();
Request request = (Request) params.get("request");
Response<Object> response = (Response<Object>) params.get("response");
// 方法一
if (groovyObject instanceof Connector) {
ContextHolder.autowireBean(groovyObject); // 对脚本java中的Autowired成员变量进行注入
Connector instance1 = (Connector) groovyObject;
instance1.endPoint(request, response);
}
// 方法二
ContextHolder.autowireBean(groovyObject);
Object[] objects = new Object[]{request,response};
groovyObject.invokeMethod("endPoint", objects);
}
} catch (Exception e) {
log.info("method-error");
}
return null;
}
备注
这个要被 groovy 解析的类/代码块,不能添加spring注解,因为它并没有被 spring 所管理。