fix: 脚本执行前直接插入 import 语句,根治 PluginContext 找不到
This commit is contained in:
@@ -5,8 +5,6 @@ import groovy.lang.Binding;
|
||||
import groovy.lang.GroovyClassLoader;
|
||||
import groovy.lang.GroovyShell;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.codehaus.groovy.control.CompilerConfiguration;
|
||||
import org.codehaus.groovy.control.customizers.ImportCustomizer;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -23,18 +21,12 @@ import java.util.*;
|
||||
public class GroovyScriptEngine {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final GroovyClassLoader classLoader;
|
||||
|
||||
static {
|
||||
ImportCustomizer imports = new ImportCustomizer();
|
||||
imports.addStarImports("groovy.json");
|
||||
imports.addStarImports("com.par.core.adapter");
|
||||
|
||||
CompilerConfiguration config = new CompilerConfiguration();
|
||||
config.addCompilationCustomizers(imports);
|
||||
|
||||
classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), config);
|
||||
}
|
||||
private static final GroovyClassLoader classLoader = new GroovyClassLoader(
|
||||
Thread.currentThread().getContextClassLoader());
|
||||
/** 脚本前缀:自动导入必要包 + PluginContext 桩 */
|
||||
private static final String SCRIPT_PREFIX =
|
||||
"import groovy.json.*\n" +
|
||||
"import com.par.core.adapter.*\n";
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Object> execute(String groovyScript, String content, String url) {
|
||||
@@ -49,7 +41,7 @@ public class GroovyScriptEngine {
|
||||
binding.setVariable("utils", new ScriptUtils());
|
||||
|
||||
GroovyShell shell = new GroovyShell(classLoader, binding);
|
||||
Object scriptResult = shell.evaluate(groovyScript);
|
||||
Object scriptResult = shell.evaluate(SCRIPT_PREFIX + groovyScript);
|
||||
|
||||
return buildResult(result, scriptResult);
|
||||
} catch (Exception e) {
|
||||
|
||||
Reference in New Issue
Block a user