import java
import
import java
import java
import java
import java
import org
import org
import org
import org
import org
import com
/**
* 簡單模擬spring的ClassPathXmlApplicationContext spring容器管理bean
*
* @author zdw
*
*/
@SuppressWarnings(
public class MyApplicationContext
{
private List<BeanDefinition> list = new ArrayList<BeanDefinition>();
private Map<String
public MyApplicationContext(String fileName)
{
this
try
{
instanceBeans();
}
catch (Exception e)
{
e
}
}
/**
* 實例化所有bean
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
*/
private void instanceBeans() throws InstantiationException
IllegalAccessException
{
for (BeanDefinition bean : list)
{
if (null != bean
sigletons
}
}
/**
* 讀取xml配置
*
* @param fileName
*/
public void readXML(String fileName)
{
SAXBuilder builder = new SAXBuilder();
URL url = this
try
{
Document doc = builder
XPath xpath = XPath
xpath
List<Element> beans = xpath
for (Element bean : beans)
{
String id = bean
String className = bean
BeanDefinition beanDefinition = new BeanDefinition(id
className);
list
}
}
catch (JDOMException e)
{
e
}
catch (IOException e)
{
e
}
}
/**
* 得到指定id的bean
*
* @param id
* @return
*/
public Object getBean(String id)
{
return sigletons
}
}
測試
public void testMyUserService()
{
MyApplicationContext ctx = new MyApplicationContext(
UserService us = (UserService) ctx
us
}
代碼下載
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28759.html