模拟Spring装载bean的方式

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 beanDefines = new ArrayList();
	
	private HashMap beans = new HashMap();
	
	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 nsMap = new HashMap();
         nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
         XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
         xsub.setNamespaceURIs(nsMap);//设置命名空间
         List 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();
        }
	}

}

 

 

 

 

 

你可能感兴趣的:(学习笔记)