Spring boot jar 加载

问题描述 投票:0回答:1

默认情况下,如果我们将 jar 插件添加为 Spring Boot 应用程序的依赖项,Spring 可以加载这些依赖项。但是我如何配置 spring 从自定义路径加载我的自定义 jar 插件。

java spring classloader spi
1个回答
0
投票

如果你想从本地加载自定义jar,你可能想尝试通过“URLClassLoader”。

这是一个从 jar 文件加载类的简单示例。

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

这里是更新。

如果你需要加载所有类,那么你可以使用

JarFile
来查找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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.