ETL/etl-groovy/src/main/java/com/etl/groovy/controller/GroovyTestController.java

49 lines
1.7 KiB
Java

package com.etl.groovy.controller;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName GrooyTestController
* @Description 描述
* @Author ZeZhang.Liu
* @Date 2024/6/26 16:58
*/
@RestController
@RequestMapping("/groovy")
public class GroovyTestController {
@GetMapping("/test")
public Object test() {
// 创建GroovyShell
GroovyShell groovyShell = new GroovyShell();
// 装载解析脚本代码
String scriptText =
"import com.etl.groovy.service.GroovyTestService\n" +
"import com.etl.groovy.util.SpringContextUtil\n" +
"\n" +
"def getBean() {\n" +
" GroovyTestService groovyTestService = SpringContextUtil.getBean(GroovyTestService.class);\n" +
" groovyTestService.removeDashesFromAddress()\n" +
"}\n" +
"\n" +
"// 如果需要,你可以在这里定义方法或变量来模拟静态变量的行为\n" +
"def getParam1() {\n" +
" return \"通过方法获取的模拟静态变量\"\n" +
"}\n";
// 解析脚本
Script script = groovyShell.parse(scriptText);
// 执行getBean方法
script.invokeMethod("getBean", null);
// 尝试获取模拟的静态变量(通过方法)
Object param1 = script.invokeMethod("getParam1", null);
return param1;
}
}