package com.bjpowernode.drp;
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.bjpowernode.drp.service.ItemService;
/**
* Bean工厂
* @author Administrator
*
*/
public class BeanFactory {
private static BeanFactory instance = new BeanFactory();
//存放产品{key=产品编号,value=具体产品实例}
private Map beans = new HashMap();
private Document doc;
private BeanFactory() {
try {
doc = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream("applicationContext.xml"));
} catch (DocumentException e) {
throw new AppException("系统错误,请联系系统管理员");
}
}
public static BeanFactory getInstance() {
return instance;
}
/**
* 根据产品标识得到产品
* @param id
* @return
*/
public Object getBean(Class c) {
synchronized(beans) {
//如果在Map存在已经创建的产品返回
if (beans.containsKey(c.getName())) {
return beans.get(c.getName());
}
//查找xml文件中id属性等于某值的bean标签
Object object = null;
try {
Element elt = (Element)doc.selectObject("//bean[@id=\"" + c.getName() + "\"]");
object = Class.forName(elt.attributeValue("class")).newInstance();
//将创建好的产品放入到Map中
beans.put(c.getName(), object);
} catch (Exception e) {
e.printStackTrace();
throw new AppException("系统错误,请联系系统管理员");
}
return object;
}
}
public static void main(String[] args) {
ItemService itemService = (ItemService)BeanFactory.getInstance().getBean(ItemService.class);
System.out.println(itemService);
}
}
最近下载更多
gogola LV1
2022年3月17日
coolliyi LV1
2022年1月27日
1760014638 LV1
2022年1月4日
nsz123456 LV11
2021年12月5日
yqzzcj LV1
2021年9月9日
zm312463 LV1
2021年4月20日
徐梓轩 LV8
2020年11月16日
putifeishu108 LV7
2020年8月11日
Crrrrryttt LV3
2020年6月2日
自行车_1 LV7
2020年4月17日
最近浏览更多
phylory
10月20日
暂无贡献等级
hmf1989
2024年8月23日
暂无贡献等级
genyuan2014 LV6
2024年5月7日
WBelong LV8
2023年12月18日
G0200887
2023年10月22日
暂无贡献等级
微信网友_6669189563338752
2023年9月28日
暂无贡献等级
wbx666 LV1
2023年9月18日
asadda LV2
2023年6月27日
pangzhihui LV14
2023年6月2日
1073931745 LV1
2022年12月13日

