关闭

模拟spring容器实例化

502人阅读 评论(0) 收藏 举报
分类:
package com.springContext;

public class SpringBean {
	private String id ;
	private String className ;
	public SpringBean(String id, String className) {
		super();
		this.id = id;
		this.className = className;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	

}
package com.springContext;

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.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

public class LuweiClassPathXmlApplicationContext {
	private List<SpringBean> beans = new ArrayList<SpringBean>() ;
	private Map<String, Object> sigletons = new HashMap<String, Object>() ;
	
	public LuweiClassPathXmlApplicationContext(String fileName) {
		this.readXmlFile(fileName);//读取xml配置文件
		this.instanceBean() ;
	}
	private void instanceBean(){//反射技术实例化bean
		for(SpringBean springBean:beans){
			if(springBean.getClassName()!=null&&!"".equals(springBean.getClassName().trim())){
				try {
					sigletons.put(springBean.getId(), Class.forName(springBean.getClassName()).newInstance()) ;//反射技术
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}

	private void readXmlFile(String fileName){
		SAXReader reader = new SAXReader() ; 
		Document document =null;
		URL xmlPath = this.getClass().getClassLoader().getResource(fileName) ;
		try {
			document = reader.read(xmlPath) ;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Map<String, String> nsMap = new HashMap<String, String>() ;
		nsMap.put("ns", "http://www.springframework.org/schema/beans") ;//加入命名空间
		XPath xPath = document.createXPath("//ns:beans/ns:bean") ;//创建beans/bean查询路径
		xPath.setNamespaceURIs(nsMap) ;//设置命名空间
		//获取文档下的所有bean节点
		List<Element> elements = xPath.selectNodes(document) ;
		for(Element element:elements){
			String id = element.attributeValue("id") ;
			String className = element.attributeValue("class") ;
			SpringBean bean = new SpringBean(id, className) ;
			beans.add(bean);
		}
	}
	public Object getBean(String beanName){
		return sigletons.get(beanName) ;
	}

}

进行代码的测试:

//使用自己写的类进行模拟spring框架的作用
//		LuweiClassPathXmlApplicationContext luweiClassPathXmlApplicationContext = new LuweiClassPathXmlApplicationContext("applicationContext.xml") ;
//		AdminService adminService = (AdminService) luweiClassPathXmlApplicationContext.getBean("adminService") ;



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5172次
    • 积分:112
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    文章存档