加载远程服务上的spring独立子模块(二)
试是否注入成功
//从父容器上下文中获取user对象
Object pluginBean =applicationContext.getBean("user");
//测试结果
String val = tryInvoke(pluginBean);
System.out.println(val);
} catch (Exception exc) {
exc.printStackTrace();
}
}
private static void setBeanClassLoader(
DefaultListableBeanFactorybeanFactory)
throws MalformedURLException {
//指明spring_user.xml配置出现的bean对象所在jar位置
String jarFilePath = "file://10.20.150.216\\share\\ebook\\j2se\\classloader\\user.jar";
URL jarUrl = new URL(jarFilePath);
URL[] urls = new URL[] { jarUrl };
URLClassLoader cl = new URLClassLoader(urls);
beanFactory.setBeanClassLoader(cl);
}
private static String tryInvoke(Object bean) throws SecurityException,
NoSuchMethodException,IllegalArgumentException,
IllegalAccessException,InvocationTargetException {
Class< > paramTypes[] = new Class[0];
Method method =bean.getClass().getDeclaredMethod("getName", paramTypes);
Object paramValues[] = new Object[0];
Object obj = method.invoke(bean, paramValues);
//.....
return (String)obj;
}
}
这里如果我们不改变BeanClassLoader会有什么问题呢?会出现classnofound异常,这个主要原因就是默认的beanfactory classloader是AppClassLoader。
3.当然还有另外一种方式,将jar中的类扫描出来,自己创建个classloader,一个个添加进去,这种方式更加灵活多变。其实还是使用spring的bean管理方式使用比较方便,已经解决了主要场景。
public static void main(String[] args) throws Exception {
URL url = new URL("jar:file:d:\\user.jar!/");
URLClassLoader uc = new URLClassLoader(new URL[]{url});
Class< > cls = uc.loadClass("com.wzucxd.User");
Object obj = cls.newInstance();
System.out.println(obj);
}