带有 Maven 的 ServiceLoader,当 pom 中没有给出依赖项时

ServiceLoader with maven, when dependency not given in the pom

我有一个maven应用程序,我喜欢使用ServiceLoader机制来加载插件。

目前我是通过在pom中添加依赖来实现的,这样依赖jar就在类路径中,ServiceLoader可以获取它。

但是如果不在 pom 中声明依赖关系,如何实现呢?

我不喜欢用每个要使用的插件来更改 pom。

我该怎么做 - 或者插件 jar 必须始终在 pom 中?

我瞎了...

我可以简单地使用 URLClassloader 从我的应用程序的文件夹加载所有插件 jar。

public class IntegrationServiceLoader {
    public static <T> ServiceLoader<T> loadIntegrations(Path path, Class<T> clazz) {
        List<URL> fileNames = new ArrayList<>();
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
            for (Path each : directoryStream) {
                fileNames.add(each.toUri().toURL());
            }
        } catch (IOException ex) {
        }
        URL[] array = fileNames.stream().toArray(size -> new URL[size]);
        ClassLoader cl = new URLClassLoader(array, IntegrationServiceLoader.class.getClassLoader());
        return ServiceLoader.load(clazz, cl);
    }
}

这是有效的,适用于现在的设置。