1.引入pom
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>3.0.9</version> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-jsr223</artifactId> <version>3.0.9</version> </dependency>
2.引入util类 具体使用场景根据需求
package com.mybatis.plus.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.*; import java.util.HashMap; import java.util.Map; /** * @Description: 执行groovy脚本 * @Author: gch * @Date: 2024/2/26 10:22 */ public class GroovyScriptUtils { private static Logger logger = LoggerFactory.getLogger(GroovyScriptUtils.class); // 查找并创建指定脚本引擎 private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy"); public static Boolean executeWithParams(String scriptContent,String methodName, Map<String, Object> params) { // 初始化Bindings 传参 Bindings bindings = engine.createBindings(); params.forEach((k, v) -> { bindings.put(k, v); }); // 执行脚本 try { engine.eval(scriptContent, bindings); // 获取执行结果 Invocable invocable = (Invocable) engine; Boolean flag = (Boolean) invocable.invokeFunction(methodName); logger.info("执行结果:{}", flag); return flag; } catch (Exception e) { throw new RuntimeException("执行Groovy脚本出错,请检查表达式是否正确", e); } } public static void testByFunction1(){ // 初始化Bindings Bindings bindings = engine.createBindings(); // 绑定参数 bindings.put("a1", 1); bindings.put("a2", 1); bindings.put("b1", 1); bindings.put("b2", 1); // 定义groovy脚本中执行方法的名称 final String scriptName = "cal"; // 定义groovy脚本内容 String expression = "(a1>2||a2>2)&&(b1>2||b2>10)"; String scriptContent = "def "+scriptName+"(){return "+expression+"}"; try { // 执行脚本 engine.eval(scriptContent, bindings); // 获取执行结果 Invocable invocable = (Invocable) engine; Boolean flag = (Boolean) invocable.invokeFunction(scriptName); System.out.println("---------------------------------------"); System.out.println("result is: " + flag); } catch (ScriptException | NoSuchMethodException e) { e.printStackTrace(); } } public static void main(String[] args) { // testByFunction(); // 定义groovy脚本中执行方法的名称 final String scriptName = "cal"; // 定义groovy脚本内容 String expression = "(a1>2||a2>2)&&(b1>2||b2>10)"; String scriptContent = "def "+scriptName+"(){return "+expression+"}"; // 绑定参数 HashMap<String, Object> map = new HashMap<>(); map.put("a1", 1); map.put("a2", 1); map.put("b1", 1); map.put("b2", 1); logger.info("执行结果:{}", executeWithParams(scriptContent, scriptName, map)); } }
标签:groovy,engine,String,示例,scriptContent,put,bindings,springBoot From: https://www.cnblogs.com/guanxiaohe/p/18033787