[英]Loading jar file at runtime from an external folder in spring boot
我有一个 spring 启动应用程序。 我想在运行时在 spring 启动应用程序上下文中从外部文件夹加载外部 jars 而不重新启动上下文。
我检查了下面的答案,它使用 class 加载器在运行时加载类。 解决方案非常古老。
只是想知道是否有其他方法可以在运行时加载 jars。
不知何故,我能够在运行时在 spring 上下文中加载 @Component 类。有人可以告诉我是否有其他更简单的方法可以实现相同的目标:
@Component
public class CustomClassLoader {
@Autowired
ConfigurableApplicationContext applicationContext;
public void loadJar() throws ClassNotFoundException {
JarClassLoader jcl = new JarClassLoader();
jcl.add("D:\\new\\test"); //loaded all the jars from test folder
Map<String, byte[]> loadedResourceMap = jcl.getLoadedResources();
Set<String> loadedSet= loadedResourceMap.keySet().stream()
.filter(s -> s.startsWith("com/test/package/ext/")).collect(Collectors.toSet());
for (String localSet : loadedSet) {
String modifiedString = localSet.replace("/", ".").replace(".class", "");
logger.info("modified string " + modifiedString);
final Class<?> loadedClass = jcl.loadClass(modifiedString);
try {
Object loadedObject = applicationContext.getAutowireCapableBeanFactory()
.createBean(loadedClass); //autowiring the loaded classes
} catch (Exception e) {
logger.info("Exception occured while loading " + modifiedString
+ " exception is" + e.getStackTrace());
}
}
}
}
您可能希望延迟加载这些依赖于外部 jars 的组件。 请检查您是否可以使用@Lazy。 下面的链接可能会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.