模拟Spring装载bean的方式
程序员文章站
2022-03-03 11:50:33
...
Spring有一个ClassPathXmlApplicationContext。来获取bena的实例。
下面模拟一下。
新建一个类叫:CoolbiClassPathXmlApplicationContext.java
代码如下:
package com.test.spring;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
public class CoolbiClassPathXmlApplicationContext
{
private ArrayList<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private HashMap<String,Object> beans = new HashMap<String,Object>();
public CoolbiClassPathXmlApplicationContext(String configLocation)
{
this.readXML(configLocation);
this.initBean();
}
private void initBean()
{
for(BeanDefinition bean : beanDefines)
{
if(bean.getClassName()!=null && !"".equals(bean.getClassName().trim()))
{
try
{
beans.put(bean.getId(), (Class.forName(bean.getClassName())).newInstance());
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
}
public Object getBean(String beanName)
{
return beans.get(beanName);
}
private void readXML(String configLocation)
{
SAXReader saxReader = new SAXReader();
Document document=null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(configLocation);
document = saxReader.read(xmlpath);
Map<String,String> nsMap = new HashMap<String,String>();
nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap);//设置命名空间
List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点
for(Element element: beans){
String id = element.attributeValue("id");//获取id属性值
String clazz = element.attributeValue("class"); //获取class属性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
beanDefines.add(beanDefine);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
上一篇: Gradle项目转Maven项目