这里使用Java SPI的方式来实现插件化,而开发的插件是一般的java Project。至于更丰富的SpringBoot插件,不一定适用。
- 在STS新建一个java project,然后,稍微改下.classpath的文件,将文件目录改成通常的形式:
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/main/resources"/>
然后新建一个Interface:
public interface TestInterface {
String sayHello(String name);
}
然后新建一个实现类:
public class HellToInsky implements TestInterface {
@Override
public String sayHello(String name) {
return "Insky say hello to " + name;
}
}
在src\main\resources\META-INF\services目录下新建一个包含interface包名和类名的文件,例如com.qb.report.TestInterface,然后在内容中添加实现类的完整名称:
com.qb.report.HellToInsky
然后导出为java jar,放在硬盘某个位置:
2. 将interface类拷贝到我们的Springboot工程中,然后添加如下代码:
@GetMapping("/testJar")
public void testJar(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("classLoader={}", this.getClass().getClassLoader());
ClassLoader cl = new URLClassLoader(new URL[] {
new URL("file:" + "D:/test.jar")}, this.getClass().getClassLoader()) ;
ServiceLoader<TestInterface> tests = ServiceLoader.load(TestInterface.class, cl);
Iterator<TestInterface> it = tests.iterator();
if (it.hasNext()) {
TestInterface test = it.next();
String ret = test.sayHello(this.getClass().getSimpleName());
log.info("ret={}", ret);
response.getWriter().append(ret);
}
}
输出结果:
classLoader=jdk.internal.loa