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

}
posted on 2019-03-20 16:08  sidesky  阅读(272)  评论(0编辑  收藏  举报