我有一个spring boot应用程序。我想在运行时在Spring Boot应用程序上下文中从外部文件夹加载外部jar,而无需重新启动上下文。
我检查了以下答案,该答案使用类加载器在运行时加载类。解决方案很旧。
How to load Classes at runtime from a folder or JAR?
只是想知道在运行时是否还有其他方式来加载jar。
答案 0 :(得分:0)
我可以在运行时在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());
}
}
}
}
答案 1 :(得分:-1)
您可能要延迟加载依赖于外部jar的这些组件。 请检查是否可以使用@Lazy。 以下链接可能会有所帮助 https://www.logicbig.com/tutorials/spring-framework/spring-core/lazy-at-injection-point.html