模拟spring创建实例

需要的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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值