在SoapUI的Groovy脚本中加载外部Jar并调用方法的问题
解决SoapUI Groovy脚本无权限运行时加载Jar包调用方法的问题
问题背景
我需要在SoapUI项目的Groovy脚本里调用Jar包内的方法,但没有管理员权限,没法把Jar放到SoapUI安装目录的../bin/ext文件夹,只能通过运行时动态加载Jar的方式实现。
之前尝试的方法及遇到的坑
我试了几种方法都踩了坑:
- 尝试通过rootLoader加载Jar
this.class.classLoader.rootLoader.addURL(new URL("file:///H://Foo-2//Foo.jar")); def cls = Class.forName("test").newInstance(); cls.add()
结果rootLoader直接是null,根本没法执行加载操作。
- 自定义URLClassLoader加载
def classLoader = ClassLoader.systemClassLoader def newClassLoader = new URLClassLoader([new File("file:///H://Foo-2//Foo.jar").toString().toURL()] as URL[], classLoader) def cls = Class.forName("test").newInstance();
运行后抛出ClassNotFoundException,找不到要调用的类,看来这个方式在SoapUI的环境里不生效。
- 尝试用SoapUI的ClasspathHacker
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context ) def classpathHacker = new com.eviware.soapui.support.ClasspathHacker () log.info "utils=" + groovyUtils mystring = "file://H://Baz.jar" com.eviware.soapui.support.ClasspathHacker.addURL( new URL(mystring) ) def cls = new bar()
这里成功加载了Jar,但我不确定怎么调用bar类里的静态方法add。
Jar包内的目标类代码
先贴一下我要调用的Jar里的bar类代码:
public class bar { public static void main(String[] args) { add(); } public static void add(){ String path = "H:" + File.separator + "Groovy" + File.separator + "hi.txt"; File f = new File(path); f.getParentFile().mkdirs(); try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } }
最终可行的解决方案
经过多次尝试,终于找到能正常运行的Groovy脚本,核心是利用SoapUI内置的ClasspathHacker工具,结合项目路径动态加载Jar:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context ) def classpathHacker = new com.eviware.soapui.support.ClasspathHacker () path = groovyUtils.getProjectPath() myfile = new java.io.File(path + "/Baz.jar") mystring = "file://" + path + "/Baz.jar" log.info "myfile=" + myfile classpathHacker.addFile( myfile ) com.eviware.soapui.support.ClasspathHacker.addFile( myfile ) com.eviware.soapui.support.ClasspathHacker.addURL( new URL(mystring) ) // 加载类并实例化调用实例方法 def instance = this.class.classLoader.loadClass( 'bar', true, false )?.newInstance() instance.add();
如果要调用静态方法add,不需要实例化对象,直接通过加载后的类调用即可:
// 调用静态方法的写法 def barClass = this.class.classLoader.loadClass('bar', true, false) barClass.add()
这个方案不需要修改SoapUI的安装目录,完全通过运行时加载实现,完美适配无管理员权限的场景。
内容的提问来源于stack exchange,提问作者John Doe
相关产品推荐
相关产品推荐

