spring-boot-classloader

11次阅读

共计 697 个字符,预计需要花费 2 分钟才能阅读完成。

最近闲暇时写了一个 hessian 小测试的工具,为了方便使用了 spring boot。该测试工具最关键的步骤是动态加载每个测试模块对应的 hessian api 的 jar 包。开始的加载代码为:

URLClassLoader loader=new URLClassLoader(new URL[]{new URL("file:"+jarPathStrategy.fileStorePath(moduleName,jarname))});
loader.loadClass(className);

在 IDE 直接运行 spring boot 的 main 函数,every thing is ok!


当我将项目编译成 jar 包,上传到测试环境执行:java -jar 后,发现通过 URLClassLoader 无法找到 hessian 的类,一顿调试排查后,IDE 依旧 OK,命令起到你 jar 依旧无法工作。这是我考虑到是不是 spring boot 的 classloader 比较特殊,不是 systemclassloader。google 一下,果不其然跟我想的一样,spring boot 的 classloader 继承体系有所变化。具体参见此大神的实验(http://hengyunabc.github.io/s…)。遂修改代码:

URLClassLoader loader=new URLClassLoader(new URL[]{new URL("file:"+jarPathStrategy.fileStorePath(moduleName,jarname))},parentClassLoader);
loader.loadClass(className); 请输入代码 

正文完
 0