zoukankan      html  css  js  c++  java
  • dynamic load jar and init spring

    public class SpringLoader {

    private Map<String, Class<?>> classMap = new HashMap<>();

    public void loadJar(String jarPath) throws IOException, ClassNotFoundException {
    File file = new File(jarPath);
    if (!file.exists()) {
    return;
    }

    JarFile jarFile = new JarFile(jarPath);
    JarEntry jarEntry;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader appClassLoader;

    URL url = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");
    System.out.println("====" + url);
    appClassLoader = new URLClassLoader(new URL[]{url}, classLoader);
    List<String> xmlList = new ArrayList<>();
    Enumeration<JarEntry> entries = jarFile.entries();

    while (entries.hasMoreElements()) {
    jarEntry = entries.nextElement();
    System.out.println(jarEntry.getName());
    if (jarEntry.getName().endsWith("spring.xml")) {
    xmlList.add("jar:" + file.toURL().toString() + "!/" + jarEntry.getName());
    System.out.println("---====" + file.getAbsolutePath());
    System.out.println("+++====" + file.toURL());
    }
    }

    Thread.currentThread().setContextClassLoader(appClassLoader);
    FileSystemXmlApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext(xmlList.toArray(new String[]{}));

    Hello hello = fileSystemXmlApplicationContext.getBean(Hello.class);
    hello.say();

        // or
        
    Class<?> clazz = appClassLoader.loadClass("com.demo.MyHello");
    Hello hello = (Hello) clazz.newInstance();
    hello.say();

    }

    public static void main(String[] args) {
    SpringLoader springLoader = new SpringLoader();
    try {
    springLoader.loadJar("target/target.jar");
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }

    }
  • 相关阅读:
    react 如何 阻止冒泡
    GitHub如何下载clone指定的tag
    git 建立一个私有模块
    如何获取域名(网址)对应的IP地址
    [翻译] JTCalendar
    将jsonModel转化为文件
    CALayer动画的暂停,恢复,以及结束时候的回调
    用标签页TitleSwitch切换不通的控制器
    设计可以多选的按钮ChooseManyButton
    设计标签选择器TitleSwitch
  • 原文地址:https://www.cnblogs.com/sidesky/p/10565565.html
Copyright © 2011-2022 走看看