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

    }
  • 相关阅读:
    软件策划书
    对开发团队的看法
    对敏捷开发的认识
    企业单位
    Pg数据库的基础安装
    Windows Server 任务计划执行.exe
    2020.04.08 重新开始
    20200211 Oracle监听启动异常
    20191225 医疗行业数据仓库
    20191224 多维数据库
  • 原文地址:https://www.cnblogs.com/sidesky/p/10565565.html
Copyright © 2011-2022 走看看