xml简易版Spring IoC

先看一下代码吧 写的也不好 后期自己在好好改正一下

package com.jzw.xmlcontext;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class MyClassPathXmlApplicationContext {
	
	//这个concurrenthashmap用于存放xml文件中信息 有 id class  目前还没有用到这个 后期打算在精选一遍
	private ConcurrentHashMap< String, String> xmlElement =new ConcurrentHashMap<String, String>();
	
	private String xmlPath;
	//先来一个构造方法
	public MyClassPathXmlApplicationContext(String xmlPath) {
		this.xmlPath = xmlPath;
	}
	//主要调用的是getBean方法  传入一个beanId
	/*
	 * 分三步 
	 * 1、解析xml文件 获取里面的bean信息
	 * 2、对比传过来的beanId 看看里面有没有对应的bean
	 * 3、通过反射调用该对象。
	 */
	//@SuppressWarnings("deprecation")
	public Object getBean(String beanId) throws Exception {
		//如果调用getBean不传参数的话 
		if (beanId == null) {
			throw new Exception("beanId 为空");
		}
		List<Element> elements = readXml();
		if(elements==null) {
			throw new Exception("xml 为空");
		}
		//然后我获取到bean节点之后需要去循环对比这个bean id
		for (Element element : elements) {
			if(element.attributeValue("id").equals(beanId)) {
				//如果有的话那么及时找到这个bean 然后就返回这个
				String className = element.attributeValue("class");
				System.out.println("获取到这个bean的class路径为:  " + className);
				//然后用过反射机制返回
				Class class1= Class.forName(className);
				return class1.newInstance();
			}
		}
		throw new Exception("没有对应的id配置");
	}
	
	public List<Element> readXml() throws DocumentException {
		SAXReader saxread = new SAXReader();
		//找到xml文件 并解析成InputStream
		InputStream inputStream = saxread.getClass().getClassLoader().getResourceAsStream(xmlPath);
		
		Document document = saxread.read(inputStream);
		
		Element rootElement = document.getRootElement(); //获取根节点
		//获取根节点下所有的子节点
	    List<Element> elements = rootElement.elements();
	    
	    return elements;
	    //我打算这样  将所有的子节点的 id class 信息存到一个ConcurrentHashMap中
	    
	}	
}

说一下过程

准备工作做完之后 

1、想办法获取xml里面的配置信息

     第一步:找到路径         InputStream inputStream = saxread.getClass().getClassLoader().getResourceAsStream(xmlPath);

      这就可以获取路径并将它解析成inputStream  (很神奇,我现在还没去看里面的原理)

      第二步  : 获取节点

       

        获取了节点之后你就可以获取其他的所有信息   获取里面的 id class 

  2、 获取id  class  对比传过来的参数beanId

         利用这个方法

          

           你就可以获取这个id里面的值  返回一个字符串  对于class 也是一样

3、  通过反射机制 获取实例对象

这个就简单了    Class.forName(className).newInstance();

          

总结  : 自己还有有很多不懂的  SAX解析xml文件  里面的属性获取   。

猜你喜欢

转载自blog.csdn.net/qq_40261771/article/details/81566826