背景
假設一個web工程有
一般我們的工程會采用spring來管理bean
這次的知識點以這個背景為例來進行講解
首先看下這樣做的一些好處
原理
user
spring_user
<bean id=
<property name=
</bean>
User
packagecom
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
}
基本思路
詳細代碼以及示例如下
public class Test {
public static void main(String[] args) {
try {
//讀取spring全局配置文件
//當然平時這裡會用ClassPathXmlApplicationContext
ApplicationContextapplicationContext = newFileSystemXmlApplicationContext(
//創建全局spring BeanFactory
DefaultListableBeanFactorybeanFactory = (DefaultListableBeanFactory)applicationContext
//獨立模塊的spring bean配置文件位置
String configurationFilePath =
//這裡可以做一個邏輯
URL url = new URL(configurationFilePath)
//建立遠程資源訪問
UrlResource urlResource = new UrlResource(url)
XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(urlResource)
String[] beanIds =xmlBeanFactory
for (String beanId : beanIds) {
//獲得的子模塊bean對象
BeanDefinition bd =xmlBeanFactory
//在這裡將子模塊bean對象注冊到父容易上下文中
beanFactory
}
//接著要進行classloader的改變
//這時候就需要將父容易中beanFactory的加載bean的classloader改變(父容易中beanFactory默認是AppClassLoader
// 以下這行設置BeanFactory的ClassLoader為URLClassLoader
setBeanClassLoader(beanFactory)
//以下是測試是否注入成功
//從父容器上下文中獲取user對象
Object pluginBean =applicationContext
//測試結果
String val = tryInvoke(pluginBean)
System
} catch (Exception exc) {
exc
}
}
private static void setBeanClassLoader(
DefaultListableBeanFactorybeanFactory)
throws MalformedURLException {
//指明spring_user
String jarFilePath =
URL jarUrl = new URL(jarFilePath)
URL[] urls = new URL[] { jarUrl };
URLClassLoader cl = new URLClassLoader(urls)
beanFactory
}
private static String tryInvoke(Object bean) throws SecurityException
NoSuchMethodException
IllegalAccessException
Class<?> paramTypes[] = new Class[
Method method =bean
Object paramValues[] = new Object[
Object obj = method
//……
return (String)obj;
}
}
這裡如果我們不改變BeanClassLoader會有什麼問題呢?會出現classnofound異常
public static void main(String[] args) throws Exception {
URL url = new URL(
URLClassLoader uc = new URLClassLoader(new URL[]{url})
Class<?> cls = uc
Object obj = cls
System
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27186.html