简体   繁体   English

在运行时从 spring 引导中的外部文件夹加载 jar 文件

[英]Loading jar file at runtime from an external folder in spring boot

I have a spring boot application.我有一个 spring 启动应用程序。 I want to load external jars from an external folder at runtime in the spring boot application context without restarting the context.我想在运行时在 spring 启动应用程序上下文中从外部文件夹加载外部 jars 而不重新启动上下文。

I checked the below answer which uses class loader to load the classes at runtime.我检查了下面的答案,它使用 class 加载器在运行时加载类。 The solution is very old.解决方案非常古老。

How to load Classes at runtime from a folder or JAR? 如何在运行时从文件夹或 JAR 加载类?

Just wanted to know if there is any other way to load jars at runtime.只是想知道是否有其他方法可以在运行时加载 jars。

Somehow I was able to load the @Component classes in the spring context at runtime.Can someone please let me know if there is any other easier way i can achieve the same:不知何故,我能够在运行时在 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());
      }
    }

  }

}

You might want to delay loading these components which are depend on the external jars.您可能希望延迟加载这些依赖于外部 jars 的组件。 Please check if you can use @Lazy.请检查您是否可以使用@Lazy。 Below link can be helpful https://www.logicbig.com/tutorials/spring-framework/spring-core/lazy-at-injection-point.html下面的链接可能会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM