1: 首先我们要利用dom4j进行xml的解析,将所有的bean的配置读取出来。
2:利用java的反射机制进行对象的实例化。
3: 直接获得对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 |
package cn.Junit.test; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.springframework.beans.factory.config.BeanDefinition; public
class MyClassPathXmlApplicationContext { private
String filemame; private
List<DefBean> list = new
ArrayList<DefBean>(); private
Map<String, Object> singletons = new
HashMap<String, Object>(); public
MyClassPathXmlApplicationContext() { super(); // TODO Auto-generated constructor stub } public
MyClassPathXmlApplicationContext(String filemame) { //1. 读取XML配置文件 this .readXML(filemame); //2.实例化对象 this .instanceBean(); } private
void instanceBean() { for
(DefBean bean : list) { try
{ singletons.put(bean.getId(), Class.forName(bean.getClassName()).newInstance()); } catch
(Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private
void readXML(String filemame) { SAXReader saxReader = new
SAXReader(); Document document = null ; try
{ URL xmlpath = this .getClass().getClassLoader() .getResource(filemame); document = saxReader.read(xmlpath); Map<String, String> nsMap = new
HashMap<String, String>(); XPath xsub = document.createXPath( "//ns:beans/ns:bean" );// 创建beans/bean查询路径 xsub.setNamespaceURIs(nsMap); // 设置命名空间 List<Element> beans = xsub.selectNodes(document); // 获取文档下所有bean节点 for
(Element element : beans) { String id = element.attributeValue( "id" ); // 获取id属性值 String clazz = element.attributeValue( "class" ); // 获取class属性值 DefBean bean = new
DefBean(id, clazz); list.add(bean); } } catch
(Exception e) { e.printStackTrace(); } } //3. 获得bean对象 public
Object getBean(String key) { return
singletons. get (key); } } |
原文:http://www.cnblogs.com/E-star/p/3556964.html