1、首先在POM文件引入对应核心groovy jar
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-jsr223</artifactId>
<version>3.0.2</version>
</dependency>
2、封装对应Groovy工具类
public class GroovyUtil {
static ScriptEngineManager factory = new ScriptEngineManager();
static ScriptEngine engine = factory.getEngineByName(Dict.GROOVY);
private GroovyUtil() {
throw new IllegalStateException("GroovyUtil class");
}
/**
* eval函数
*
* @param script groovy脚本
* @param textMap 条件入参
* @return
*/
public static Object eval(String script, Map<String, Object> textMap) {
try {
Bindings binding = engine.createBindings();
for (Iterator<String> iter = textMap.keySet().iterator(); iter.hasNext(); ) {
String key = iter.next();
binding.put(key, textMap.get(key));
}
return engine.eval(script, binding);
} catch (Exception e) {
throw new ScriptException("groovy脚本执行异常", e);
}
}
}