objPool = Collections.synchronizedMap(new HashMap());
//保存配置文件中对应的文档对象
private Document doc;
//保存配置文件里面的根元素
private Element root;
/**
*
*/
public MyXmlApplicationContextUtil() {
super();
}
/**
*
*/
public MyXmlApplicationContextUtil(String filePath)throws Exception{
SAXReader reader = new SAXReader();
doc = reader.read(new File(filePath));
root = doc.getRootElement();
initPool();
initProp();
}
public Object getBean(String name) throws BeansException {
Object target = objPool.get(name);
Object obj = null;
if(target.getClass() != String.class){
obj = target;
}else{
String clazz = (String)target;
try{
obj = Class.forName(clazz).newInstance();
}catch(Exception e){
e.printStackTrace();
}
}
return obj;
}
private void initPool()throws Exception{
for(Object obj:root.elements()){//遍历每个bean元素
Element ele = (Element)obj;
String beanId = ele.attributeValue("id");
String beanClazz = ele.attributeValue("class");
String beanScope = ele.attributeValue("scope");
if(beanScope == null || beanScope.equals("singleton")){
objPool.put(beanId, Class.forName(beanClazz).newInstance());
}else{
objPool.put(beanId, beanClazz);
}
}
}
private void initProp()throws Exception{
for(Object obj:root.elements()){//遍历每个bean元素
Element ele = (Element)obj;
String beanId = ele.attributeValue("id");
String beanScope = ele.attributeValue("scope");
if(beanScope == null || beanScope.equals("beanScope")){
Object bean = objPool.get(beanId);
for(Object prop:ele.elements()){
Element propElem = (Element)prop;
String propName = propElem.attributeValue("name");
String propVal = propElem.attributeValue("value");
String propRef = propElem.attributeValue("ref");
String propNameOfFirstLetter = propName.substring(0,1).toUpperCase()+propName.substring(1);
if(propVal != null && propVal.length()>0){
Method setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, String.class);
setter.invoke(bean, propVal);
}
if(propRef !=null && propRef.length()>0){
Object target = objPool.get(propRef);
if(target == null){};
Method setter = null;
for(Class superInterface:target.getClass().getInterfaces()){
try{
setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, superInterface);
setter.invoke(bean, propVal);
break;
}catch(NoSuchMethodException e){
continue;
}
}
if(setter == null){
setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, target.getClass());
}
setter.invoke(bean, propVal);
}
}
}else{
//objPool.put(beanId, beanClazz);
}
}
}
public static void main(String[] args)throws Exception{
ApplicationContext ac = new MyXmlApplicationContextUtil("D:\\Myeclipse6.5\\webBookShop\\WebRoot\\bean.xml");
StudentAction s = (StudentAction)ac.getBean("StudentAction");
System.out.println(s);
}
}