0

I have a spring boot application . I want to load external jars from an external folder at runtime in the spring boot application context without restarting the context.

I checked the below answer which uses class loader to load the classes at runtime . The solution is very old.

How to load Classes at runtime from a folder or JAR?

Just wanted to know if there is any other way to load jars at runtime.

Umesh Sanwal
  • 681
  • 4
  • 13

2 Answers2

0

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:

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

  }

}
Umesh Sanwal
  • 681
  • 4
  • 13
  • The shortcoming in this approach is that while autowiring programatically the order of autowiring is not known hence can cause failure when there are multiple dependent components to be autowired. If anyone has some way to do this , would be helpful. – Umesh Sanwal Aug 21 '20 at 13:42
  • Which JarClassLoader do you use? – Burner Nov 03 '22 at 07:42
-1

You might want to delay loading these components which are depend on the external jars. Please check if you can use @Lazy. Below link can be helpful https://www.logicbig.com/tutorials/spring-framework/spring-core/lazy-at-injection-point.html