导入依赖
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
使用java反射机制来实现从xml配置文件中获取bean对象还原spring获取bean对象方式
通过Dom4j来读取xml中的配置信息,然后动态生成类创建对象
package demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ApplicationContext {
//是缓存Spring容器的Bean对象
private Map<String,Object> beans=new HashMap<String,Object>();
/**
* 利用配置文件初始化当前容器
* 利用xml配置文件初始化全部的bean对象
* @throws DocumentException
* @throws IOException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*
*/
public ApplicationContext(String xml) throws DocumentException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
//利用DOM4j读取XML文件
//解析XML文件内容,得到Bean的类名
//和Bean的ID,
//根据类名动态加载类并创建对象
//将对象和对应的ID添加到map中
//从Resource(classpath中读取流)
InputStream in =getClass().getClassLoader().getResourceAsStream(xml);
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
in.close();
//解析xml:<beans><bean>..
Element root= doc.getRootElement();
//读取根元素中全部的bean子元素.
List<Element> list = root.elements("bean");
for(Element e:list){
//e就是bean元素 id属性和class属性
String id = e.attributeValue("id");
String className = e.attributeValue("class");
//动态加载类,动态创建对象
Class cls = Class.forName(className);
Object bean = cls.newInstance();
beans.put(id, bean);
}
}
public Object getBean(String id){
//根据id在map查找对象,并返回对象A
return beans.get(id);
}
//泛型方法:优点是可以减少一次类型转换
public<T> T getBean(String id,Class<T> cls){
return (T)beans.get(id);
}
}
自定义xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="foo" class="demo.Foo"></bean>
<bean id="date" class="java.util.Date"/>
<bean id="testCase" class="demo.TestCase"/>
</beans>