grails调用groovy脚本
原创
©著作权归作者所有:来自51CTO博客作者friendan的原创作品,请联系作者获取转载授权,否则将追究法律责任
参考文章:
http://www.poorren.com/java-groovy-dynamic-algorithm/
grails本身就是使用groovy开发的,所以调用groovy脚本也是很方便的。
我封装好的类如下:
import grails.transaction.Transactional
@Transactional
class GroovyScriptUtilsService {
def grailsApplication
static String scriptRootDir = [] // 脚本文件所在目录
static GroovyScriptEngine groovyScriptEngine
def init(){
scriptRootDir = getScriptDir()
groovyScriptEngine = new GroovyScriptEngine(scriptRootDir)
println("scriptRootDir=${scriptRootDir}")
}
/**
* 调用Groovy脚本文件中的指定方法
* @param scriptFileName 脚本文件名称,如:aaa.groovy
* @param methodName 方法名称
* @param args 方法参数
* @return
*/
@Transactional
def invokeMethod(String scriptFileName, String methodName, Object args = null) throws Exception{
if(!groovyScriptEngine){
init()
}
def ret = null
Class scriptClass = null
GroovyObject scriptInstance = null
try {
scriptClass = groovyScriptEngine.loadScriptByName(scriptFileName)
scriptInstance = (GroovyObject)scriptClass.newInstance()
ret = scriptInstance.invokeMethod(methodName, args)
}
catch (Exception ex) {
ex.printStackTrace()
}
return ret;
}
String getScriptDir(){
return getRealPath("groovyScript")
}
String getRealPath(String relativePath){
String result
try {
result = grailsApplication.getMainContext().servletContext.getRealPath("/") + relativePath
File dirDst = new File(result)
if (!dirDst.exists()) {
dirDst.mkdirs()
}
}
catch (Exception ex) {
ex.printStackTrace()
}
return result
}
}
-------------------------------------------------------------------------------------------
调用例子:
def ScrapeService scrapeService
def result = groovyScriptUtilsService.invokeMethod("test.groovy", "hello");
println("result=${result}")
Object args = ["ok"] // 多个参数时:Object args = ["ok", "11", "222"]
result = groovyScriptUtilsService.invokeMethod("test.groovy", "hello", args);
println("result=${result}")
-----------------------------------------------------------------------------------------------------------------
脚本文件test.groovy:
def hello(){
return "无参hello"
}
def hello(str){
return "有参hello,参数=${str}"
}