思路
- 利用
dom4j
读取 beans.xml
配置文件 - 获取到文件中配置的实体类全路径,通过反射生成对象
- 将该对象放入
ConcurrentHashMap
容器中,并提供一个getBean
方法,可以通过id
获取到该对象
代码
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class ApplicationContext {
private ConcurrentHashMap<String, Object> singletonObjects =
new ConcurrentHashMap<>();
public ApplicationContext(String iocBeanXmlFile) throws Exception {
String path = this.getClass().getResource("/").getPath();
Document document = saxReader.read(new File(path + iocBeanXmlFile));
Element rootElement = document.getRootElement();
Element bean = (Element)rootElement.elements("bean").get(0);
String id = bean.attributeValue("id");
String classFullPath = bean.attributeValue("class");
List<Element> property = bean.elements("property");
Integer monsterId = Integer.parseInt(property.get(0).attributeValue("value"));
String name = property.get(1).attributeValue("value");
String skill = property.get(2).attributeValue("value");
Class<?> aClass = Class.forName(classFullPath);
Monster o = (Monster)aClass.newInstance();
o.setMonsterId(monsterId);
o.setName(name);
o.setSkill(skill);
singletonObjects.put(id,o);
}
public Object getBean(String id) {
return singletonObjects.get(id);
}
}
测试
public class ApplicationContextTest {
public static void main(String[] args) throws Exception {
ApplicationContext ioc = new ApplicationContext("beans.xml");
Monster monster01 = (Monster)ioc.getBean("monster01");
System.out.println("monster01=" + monster01);
System.out.println("monster01.name=" + monster01.getName());
System.out.println("ok");
}
}