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

    }
  • 相关阅读:
    Asp.NET调用有道翻译API
    JSON C# Class Generator ---由json字符串生成C#实体类的工具
    让jQuery的contains方法不区分大小写
    javascript parseUrl函数(来自国外的获取网址url参数)
    typescript
    webpack 第二部分
    express node 框架介绍
    webpack 最新版
    es6 字符串 对象 拓展 及 less 的语法
    es6 的数组的方法
  • 原文地址:https://www.cnblogs.com/sidesky/p/10565565.html
Copyright © 2011-2022 走看看