Spring boot jar loading

83 Views Asked by At

By default if we add jar plugin as dependency to our spring boot app, spring can load these dependenies. But how can I configure spring to load my custom jar plugin from custom paths.

1

There are 1 best solutions below

5
great-jin On

If you want to load a custom jar from local, you may want to try through the "URLClassLoader".

Here is a simple example of loading a class from jar file.

@Test
public void demo() throws Exception {
    String location = "the-path-to-your-jar";
    Path path = Paths.get(location);
    URLClassLoader classLoader = new URLClassLoader(new URL[]{path.toUri().toURL()});
    classLoader.loadClass("your-class-full-qulify-name");
}

Here is update.

If you need to load all classes, then you can use JarFile to find all classes in a jar.

public Set<String> getClassNamesFromJarFile(File file) throws IOException {
    Set<String> classNames = new HashSet<>();
    try (JarFile jarFile = new JarFile(file)) {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            if (jarEntry.isDirectory()) {
                continue;
            }
            String jarName = jarEntry.getName();
            if (jarName.endsWith(".class")) {
                String className = jarName.replace("/", ".");
                classNames.add(className);
            }
        }
        return classNames;
    }
}