标签:des io ar os java for sp strong div
实现Spring中BeanFactory的案例
1.设计模式(工厂)
2.jdom
3.Java反射机制
1.beans.xml
2.DAO
3.Impl
4.Service
5.BeanFactory
6.ClassPathXmlApplication
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> beans = new HashMap<String, Object>();
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb = new SAXBuilder();
// 构造文档对象
Document doc = sb.build(this.getClass().getClassLoader()
.getResourceAsStream("beans.xml"));
// 获取元素HD
Element root = doc.getRootElement();
// 取得名字为bean的所有元素
List list = root.getChildren("bean");
//
for (int i = 0; i < list.size(); i++) {
Element element = (Element) list.get(i);
String id = element.getAttributeValue("id");
String classes = element.getAttributeValue("class");
Object o = Class.forName(classes).newInstance();
System.out.println(id);
System.out.println(classes);
beans.put(id, o);
for (Element propertyElement : (List<Element>) element
.getChildren("property")) {
String name = propertyElement.getAttributeValue("name");
String bean = propertyElement.getAttributeValue("bean");
Object beanObject = beans.get(bean);
String methodName = "set" + name;
System.out.println("method name = " + methodName);
Method m = o.getClass().getMethod(methodName,
beanObject.getClass().getInterfaces()[0]);
m.invoke(o, beanObject);
}
}
}
/*
* (non-Javadoc)
*
* @see com.yg.Spring.BeanFactory#getBean(java.lang.String)
*/
@Override
public Object getBean(String id) {
// TODO Auto-generated method stub
return beans.get(id);
}
}
7.Test
标签:des io ar os java for sp strong div
原文地址:http://www.cnblogs.com/yg-Manager/p/4070913.html