public class MyClassPathXmlApplicationContext {
private List<XmlBeanDefinition> beanDefinitions = new ArrayList<XmlBeanDefinition>();
private Map<Object, Object> sigletons = new HashMap<Object, Object>();
public MyClassPathXmlApplicationContext(String fileName) {
this.readXmlFile(fileName);// 获取XML文件下的借点属性
this.instanceBeans();// 利用反射机制实例化bean
}
/**
* bean 实例化
*/
private void instanceBeans(){
for ( XmlBeanDefinition beanDefinition : beanDefinitions) {
try {
if(beanDefinition.getName() != null && !"".equals(beanDefinition.getName())){
sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getName()).newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取XML信息
* @param fileName
*/
@SuppressWarnings("unchecked")
private void readXmlFile(String fileName) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
URL xmlPath = this.getClass().getClassLoader().getResource(fileName); // 获取相对路径
document = saxReader.read(xmlPath); // 读取xml文件
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans"); // 加入命名空间
XPath xPath = document.createXPath("//ns:beans/ns:bean"); // 创建查询路径
xPath.setNamespaceURIs(nsMap); // 设置命名空间
List<Element> beans = xPath.selectNodes(document); // 获取所有节点
for (Element element : beans) {
String id = element.attributeValue("id");
String clazz = element.attributeValue("class");
XmlBeanDefinition xmlBeanDefinition = new XmlBeanDefinition(id, clazz);
beanDefinitions.add(xmlBeanDefinition);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取bean实例
* @param beanName
* @return
*/
public Object getBean(String beanName){
return this.sigletons.get(beanName);
}
package com.heying.service;
import java.util.ArrayList;
import java.util.List;
public class XmlBeanDefinition {
private String id;
private String name;
public XmlBeanDefinition(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
建立一个junit测试类:
@Test
public void initTest() {
try {
MyClassPathXmlApplicationContext applicationContext = new MyClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService) applicationContext.getBean("personService");
personService.save();
System.out.println(personService.getClass());
} catch (Exception e) {
e.printStackTrace();
}
}