package com.wenwen.drp.beanfactory;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.wenwen.drp.basedata.dao.ItemDao;
import com.wenwen.drp.basedata.manager.ItemManager;
public class BeanFactory {
/*
*装下所用的dao对象
* */
private Map daoMap = new HashMap();
/*
* 装下所有的service对象
* */
private Map serviceMap = new HashMap();
private static BeanFactory factory = new BeanFactory();
private final String config_file="bean_config.xml";
private Document doc;
/*
* 初始化时将bean_config.xml读取到内存当中
* */
public BeanFactory(){
SAXReader reader=new SAXReader();
try {
doc = reader.read(Thread.currentThread().getContextClassLoader()
.getResourceAsStream(config_file));
} catch (DocumentException e) {
e.printStackTrace();
}
}
/*
* 单例化创建工厂
* */
public static BeanFactory newInstanse(){
return factory;
}
/*
* 拿到dao的完全路径,反射机制创建对象
* */
///Element beanElt = (Element)doc.selectSingleNode("//service[@id=\"" + serviceId + "\"]");
public Object getInstanceDao(String daoId){
Object dao = null;
//若daoMap中存在daoId,说明已经有了这个dao,则直接返回这个daoMap即可
if(daoMap.containsKey("daoId"))
return daoMap;
Element elt = (Element) doc.selectSingleNode("//dao[@id=\""+daoId+"\"]");
String className = elt.attributeValue("class");
try {
dao=Class.forName(className).newInstance();
daoMap.put(daoId, dao);
} catch (Exception e) {
e.printStackTrace();
}
//将创建好多的对象放到Map中
return dao;
}
/*
* 创建mservice
* */
public Object getInstanceService(String serviceId){
Object service = null;
//若serviceMap中存在serviceId,说明已经有了这个service,则直接返回这个serviceMap即可
if(serviceMap.containsKey("serviceId"))
return serviceMap;
Element elt = (Element) doc.selectSingleNode("//service[@id=\""+serviceId+"\"]");
String className = elt.attributeValue("class");
try {
service=Class.forName(className).newInstance();
serviceMap.put(serviceId, service);
} catch (Exception e) {
e.printStackTrace();
}
//将创建好多的对象放到Map中
return service;
}
public static void main(String[] args){
ItemDao itemdao = (ItemDao) factory.newInstanse().getInstanceDao("itemdao");
System.out.println(itemdao);
ItemManager manager = (ItemManager) factory.newInstanse().getInstanceService("itemManager");
System.out.println(manager);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<bean>
<dao id="itemdao" class="com.wenwen.drp.basedata.dao.Dao4OracleImpl"/>
<service id="itemManager" class="com.wenwen.drp.basedata.manager.ItemManager"/>
</bean>