Groovy 脚本与spring

43 阅读1分钟

加载脚本

GroovyClassLoader

CompilerConfiguration

Binding

GroovyShell

Script

@RestController
@RequestMapping("/groovy")
@Slf4j
public class GroovyController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping(value = "/omnipotent", method = RequestMethod.POST)
    public ResponseVo<String> groovy(@RequestBody String content){
        try {
            GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
            CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
            compilerConfiguration.setSourceEncoding("utf-8");

            Binding groovyBinding = new Binding();
            applicationContext.getBeansOfType(Object.class).forEach(groovyBinding::setVariable);

            GroovyShell groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
            Script script = groovyShell.parse(content);
            return ResponseVo.success(String.valueOf(script.run()));
        } catch (Exception e) {
            log.error("groovy脚本执行失败: {}", e);
            return ResponseVo.fail(e.getMessage());
        }
    }
}


image.png