Spring webapp 加载插件:ClassNotFoundException
Spring webapp loading plugins: ClassNotFoundException
我正在编写一个 Spring 网络应用程序,它在运行时加载插件文件。这些插件 类 实现了 IPlugin
。但是,在运行时加载插件时,我得到一个 ClassNotFoundException
(IPlugin
cannot be found).
接口 IPlugin
位于我的网络应用程序的一个包中。为了构建一个插件,我将接口导出到一个 jar 文件并将其包含在插件的构建路径中。
在我的网络应用程序中,使用 URLClassLoader
:
加载插件
URL fileUrl = jar.toURI().toURL();
String jarUrl = "jar: " + fileUrl + "!/";
URL[] urls = new URL[] {new URL(jarUrl)};
URLClassLoader loader = new URLClassLoader(urls);
IPlugin plugin = (IPlugin) Class.forName(clazz, true, loader).newInstance();
如何使接口在运行时可用?
编辑:
如果我将包含 IPlugin.class
的 jar 与插件一起加载,它确实有效。但这真的有必要吗?
我认为如果不在顶部导入就无法使用 IPlugin
只需将 IPlugin.java 带入您的代码中,并使用相同的包名,这没有错
您可以直接使用完整文件路径通过 URLClassLoader 加载 JAR
试试下面的代码
URL[] classLoaderUrls = new URL[]{new URL("file:///<your directory path>/<your filename>.jar")};
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
Class<?> beanClass = urlClassLoader.loadClass("com.my.MyImplementation");
Constructor<?> constructor = beanClass.getConstructor();
Object beanObj = constructor.newInstance();
尝试输入强制转换,如果您在顶部的导入中有 IPlugin.java,这将有效
IPlugin plugin = (IPlugin)beanObj;
否则你需要使用反射
Method method = beanClass.getMethod("myMethod");
method.invoke(beanObj);
我找到了解决方案,我必须像这样设置父 class 加载器:new URLClassLoader(URLs, getClass().getClassLoader())
。在 webapp 中存在 IPlugin
接口就足够了,在 WEB-INF/lib.
中不需要额外的 jar
我正在编写一个 Spring 网络应用程序,它在运行时加载插件文件。这些插件 类 实现了 IPlugin
。但是,在运行时加载插件时,我得到一个 ClassNotFoundException
(IPlugin
cannot be found).
接口 IPlugin
位于我的网络应用程序的一个包中。为了构建一个插件,我将接口导出到一个 jar 文件并将其包含在插件的构建路径中。
在我的网络应用程序中,使用 URLClassLoader
:
URL fileUrl = jar.toURI().toURL();
String jarUrl = "jar: " + fileUrl + "!/";
URL[] urls = new URL[] {new URL(jarUrl)};
URLClassLoader loader = new URLClassLoader(urls);
IPlugin plugin = (IPlugin) Class.forName(clazz, true, loader).newInstance();
如何使接口在运行时可用?
编辑:
如果我将包含 IPlugin.class
的 jar 与插件一起加载,它确实有效。但这真的有必要吗?
我认为如果不在顶部导入就无法使用 IPlugin
只需将 IPlugin.java 带入您的代码中,并使用相同的包名,这没有错
您可以直接使用完整文件路径通过 URLClassLoader 加载 JAR
试试下面的代码
URL[] classLoaderUrls = new URL[]{new URL("file:///<your directory path>/<your filename>.jar")};
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
Class<?> beanClass = urlClassLoader.loadClass("com.my.MyImplementation");
Constructor<?> constructor = beanClass.getConstructor();
Object beanObj = constructor.newInstance();
尝试输入强制转换,如果您在顶部的导入中有 IPlugin.java,这将有效
IPlugin plugin = (IPlugin)beanObj;
否则你需要使用反射
Method method = beanClass.getMethod("myMethod");
method.invoke(beanObj);
我找到了解决方案,我必须像这样设置父 class 加载器:new URLClassLoader(URLs, getClass().getClassLoader())
。在 webapp 中存在 IPlugin
接口就足够了,在 WEB-INF/lib.