java - ServiceLoader、URLClassLoader 和 Spring : java. lang.NoClassDefFoundError

标签 java spring serviceloader

我正在尝试加载一个外部 module.jar,它实现了我的主 spring 应用程序的接口(interface)。

因此我实现了this solution

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
    File loc = new File("plugins");

    File[] flist = loc.listFiles(new FileFilter() {
        public boolean accept(File file) {return file.getPath().toLowerCase().endsWith(".jar");}
    });

    URL[] urls = new URL[flist.length];
    for (int i = 0; i < flist.length; i++) {
        try {
            urls[i] = flist[i].toURI().toURL();
            System.out.println(flist[i].toURI().toURL().toString());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    URLClassLoader ucl = new URLClassLoader(urls);

    ServiceLoader<DeviceInterface> sl = ServiceLoader.load(DeviceInterface.class, ucl);
    Iterator<DeviceInterface> apit = sl.iterator();
    while (apit.hasNext())
        System.out.println(apit.next().getName());
}

不幸的是,这会引发此异常:

java.lang.NoClassDefFoundError: de/maxrakete/james/device/domain/DeviceInterface

我是否应该将我的主应用程序声明为模块中的依赖项?目前我的模块只有自己的依赖项。

我在网上找到的资源对于这个问题并不是很清楚。

最佳答案

可能是springboot打包问题。尝试将重新打包添加到您的 Maven 构建中

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <classifier>exec</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>

关于java - ServiceLoader、URLClassLoader 和 Spring : java. lang.NoClassDefFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067222/

相关文章:

java - Web 应用程序充当 Restfull 应用程序的方法

java - 多线程 Swing 事件调度程序线程

Spring Boot + Spring Security + 分层角色

java - 谁能帮我写一个更新查询

java - 提供者不是 docker 容器内的子类型

java - 如何确保我使用的是 "server"JVM?

java - deeplearning4j - 使用 Word2Vec 进行命名实体识别

Spring @Async 与 CompletableFuture

java - 如何将自定义文本文件包含到构建过程中

java - ServiceLoader找不到插件