需要的jar包:spring.jar commons-logging.jar jdom.jar junit.jar
MyClassPathXMLApplicationContext.java
package springCreatBean;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
/*
* 模拟spring的根据配置文件创建bean的功能
*/
public class MyClassPathXMLApplicationContext {
private List<BeanType> beans = new ArrayList<BeanType>();
private Map<String,Object> map = new HashMap<String,Object>();
private void xmlParse(String location) throws Exception{
/*
* jdom解析xml文件
*/
SAXBuilder builder = new SAXBuilder();
InputStream file = new FileInputStream(location);
Document document = builder.build(file);//获得文档对象
Element root = document.getRootElement();//获得根节点
List<Element> list = root.getChildren();
for(Element e:list) {
String beanName = e.getAttributeValue("id");
String beanClass = e.getAttributeValue("class");
BeanType bt = new BeanType();
bt.setBeanClass(beanClass);
bt.setBeanName(beanName);
beans.add(bt);
}
}
private void creatBean() throws Exception {
for(BeanType bean : beans){
if(bean.getBeanClass()!=null&&!bean.getBeanClass().trim().equals("")){
map.put(bean.getBeanName(), Class.forName(bean.getBeanClass()).newInstance());
}
}
}
/*
* 在实例化对象的时候直接读取配置文件,获取所有的<bean>信息
* 并且将其实例化存放到一个HashMap中
*/
public MyClassPathXMLApplicationContext(String location) throws Exception {
this.xmlParse(location);
this.creatBean();
}
/*
* 提供一个取实例的方法
*/
public Object get(String beanName){
return map.get(beanName);
}
}
/*
* 这个类用于封装<bean>的信息,封装好的对象存放到ArrayList中
*/
class BeanType{
private String beanName;
private String beanClass;
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanClass() {
return beanClass;
}
public void setBeanClass(String beanClass) {
this.beanClass = beanClass;
}
}
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="userService" class="serviceImpl.UserServiceImpl">
</bean>
</beans>
测试代码:
public class test {
@Test
public void instanceSpring() throws Exception{
MyClassPathXMLApplicationContext bf = new MyClassPathXMLApplicationContext("src/beans.xml");
UserService userService = (UserService) bf.get("userService");
userService.save();
}