Search code examples
javamavenserviceloader

ServiceLoader with maven, when dependency not given in the pom


I have a maven application and I like to use the ServiceLoader mechanism to load plugins.

Currently I achieve this by adding the dependency to the pom, so that the dependency jar is in the classpath and the ServiceLoader can pick it up.

But how can this be achieved without declaring the dependency in the pom ?

I don't like to change the pom with every plugin that shall be used.

How can I do this - or must the plugin jar always be in the pom ?


Solution

  • I was blind...

    I simply can use the URLClassloader to load all plugin jars from a folder of my application.

    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);
        }
    }
    

    This is valid and works for the setup now.