package com.spring;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import com.vo.BeanDefinition;
/**
* 简单模拟spring的ClassPathXmlApppcationContext spring容器管理bean
*
* @author
*
*/
@SuppressWarnings(“unchecked”)
pubpc class MyApppcationContext
{
private List pst = new ArrayList();
private Map sigletons = new HashMap();
pubpc MyApppcationContext(String fileName)
{
this.readXML(fileName);
try
{
instanceBeans();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 实例化所有bean
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
*/
private void instanceBeans() throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
for (BeanDefinition bean : pst)
{
if (null != bean.getClassName() && bean.getClassName().length() 》 0)
sigletons.put(bean.getId(), Class.forName(bean.getClassName())
.newInstance());
}
}
/**
* 读取xml配置
*
* @param fileName
*/
pubpc void readXML(String fileName)
{
SAXBuilder builder = new SAXBuilder();
URL url = this.getClass().getClassLoader().getResource(fileName);
try
{
Document doc = builder.build(url);
XPath xpath = XPath.newInstance(“//ns:beans/ns:bean”);
xpath.addNamespace(“ns”,
“http://www.springframework.org/schema/beans”);
List beans = xpath.selectNodes(doc);
for (Element bean : beans)
{
String id = bean.getAttributeValue(“id”);
String className = bean.getAttributeValue(“class”);
BeanDefinition beanDefinition = new BeanDefinition(id,
className);
pst.add(beanDefinition);
}
}
catch (JDOMException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 得到指定id的bean
*
* @param id
* @return
*/
pubpc Object getBean(String id)
{
return sigletons.get(id);
}
}
测试:
@Test
pubpc void testMyUserService()
{
MyApppcationContext ctx = new MyApppcationContext(“beans.xml”);
UserService us = (UserService) ctx.getBean(“userService”);
us.print();
}
-5-3-1-+1+3+5评分:0
① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;
② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。