手写Spring的IOC容器和DI依赖注入

1. Java解析xml文件


Spring都是基于xml文件的方式来操作。因此,Java解析xml文件是必须的!

XML的解析方式分为四种:1、DOM解析;2、SAX解析;3、JDOM解析;4、DOM4J解析。

其中前两种属于基础方法,是官方提供的平台无关的解析方式;后两种属于扩展方法,它们是在基础的方法上扩展出来的,只适用于java平台。

接下来写一个xml文件,通过四种不同的方式来解析该xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book id="1">
        <name>三国演义</name>
        <author dynasty="yuan">罗贯中</author>
        <price>89</price>
    </book>
    <book id="2">
        <name>安徒生童话</name>
        <year>2004</year>
        <price>77</price>
        <language>English</language>
    </book>    
</bookstore>

2. 方式一:DOM解析


在这里插入图片描述

package com.itholmes.xmlToJava;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOM_parse {
	public static void main(String[] args) throws SAXException, IOException {
		//创建一个DocumentBuilderFactory的对象
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			//创建一个DocumentBuilder的对象
			DocumentBuilder db = dbf.newDocumentBuilder();
			//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
			Document document = db.parse("src/resources/books.xml");
			//获取所有book节点的集合
			NodeList bookList = document.getElementsByTagName("book");
			//获取bookList的长度,里面有多少个book标签节点。
			System.out.println("获取bookList的长度:"+bookList.getLength());
			
			//遍历每一个book节点
			for(int i=0;i<bookList.getLength();i++) {
				System.out.println("=======遍历第"+ (i + 1) + "本书的内容=======");
				//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始
				Node book = bookList.item(i);
				
				//获取book节点的所有属性集合
				NamedNodeMap attrs = book.getAttributes();
				System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
				
                //遍历book的属性
                for (int j = 0; j < attrs.getLength(); j++) {
                    //通过item(index)方法获取book节点的某一个属性
                    Node attr = attrs.item(j);
                    //获取属性名
                    System.out.print("属性名:" + attr.getNodeName());
                    //获取属性值
                    System.out.println("--属性值" + attr.getNodeValue());
                }
                
                //解析book节点的子节点
                NodeList childNodes = book.getChildNodes();
                //遍历childNodes获取每个节点的节点名和节点值
                System.out.println("第" + (i+1) + "本书共有" + childNodes.getLength() + "个子节点");
                for (int k = 0; k < childNodes.getLength(); k++) {
                    //区分出text类型的node以及element类型的node
                    if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
                        //获取了element类型节点的节点名
                        System.out.print("第" + (k + 1) + "个节点的节点名:" + childNodes.item(k).getNodeName());
                        //获取了element类型节点的节点值
                        System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue());
                        //System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
                    }
                }
                System.out.println("======结束遍历第" + (i + 1) + "本书的内容======");
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3. 方式二:SAX解析


在这里插入图片描述

public class SAXTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            SAXParserHandler handler = new SAXParserHandler();
            parser.parse("books.xml", handler);
            System.out.println("~!~!~!共有" + handler.getBookList().size()
                    + "本书");
            for (Book book : handler.getBookList()) {
                System.out.println(book.getId());
                System.out.println(book.getName());
                System.out.println(book.getAuthor());
                System.out.println(book.getYear());
                System.out.println(book.getPrice());
                System.out.println(book.getLanguage());
                System.out.println("----finish----");
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public class SAXParserHandler extends DefaultHandler {
    String value = null;
    Book book = null;
    private ArrayList<Book> bookList = new ArrayList<Book>();
    public ArrayList<Book> getBookList() {
        return bookList;
    }

    int bookIndex = 0;
    /**
     * 用来标识解析开始
     */
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();
        System.out.println("SAX解析开始");
    }
    
    /**
     * 用来标识解析结束
     */
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
        System.out.println("SAX解析结束");
    }
    
    /**
     * 解析xml元素
     */
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //调用DefaultHandler类的startElement方法
        super.startElement(uri, localName, qName, attributes);
        if (qName.equals("book")) {
            bookIndex++;
            //创建一个book对象
            book = new Book();
            //开始解析book元素的属性
            System.out.println("======================开始遍历某一本书的内容=================");
            //不知道book元素下属性的名称以及个数,如何获取属性名以及属性值
            int num = attributes.getLength();
            for(int i = 0; i < num; i++){
                System.out.print("book元素的第" + (i + 1) +  "个属性名是:"
                        + attributes.getQName(i));
                System.out.println("---属性值是:" + attributes.getValue(i));
                if (attributes.getQName(i).equals("id")) {
                    book.setId(attributes.getValue(i));
                }
            }
        }
        else if (!qName.equals("name") && !qName.equals("bookstore")) {
            System.out.print("节点名是:" + qName + "---");
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        //调用DefaultHandler类的endElement方法
        super.endElement(uri, localName, qName);
        //判断是否针对一本书已经遍历结束
        if (qName.equals("book")) {
            bookList.add(book);
            book = null;
            System.out.println("======================结束遍历某一本书的内容=================");
        }
        else if (qName.equals("name")) {
            book.setName(value);
        }
        else if (qName.equals("author")) {
            book.setAuthor(value);
        }
        else if (qName.equals("year")) {
            book.setYear(value);
        }
        else if (qName.equals("price")) {
            book.setPrice(value);
        }
        else if (qName.equals("language")) {
            book.setLanguage(value);
        }
    }
    
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, length);
        value = new String(ch, start, length);
        if (!value.trim().equals("")) {
            System.out.println("节点值是:" + value);
        }
    }
}

4. 方式三:JDOM解析


在这里插入图片描述

public class JDOMTest {
    private static ArrayList<Book> booksList = new ArrayList<Book>();
    /**
     * @param args
     */
    public static void main(String[] args) {
        // 进行对books.xml文件的JDOM解析
        // 准备工作
        // 1.创建一个SAXBuilder的对象
        SAXBuilder saxBuilder = new SAXBuilder();
        InputStream in;
        try {
            // 2.创建一个输入流,将xml文件加载到输入流中
            in = new FileInputStream("src/resources/books.xml");
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            // 3.通过saxBuilder的build方法,将输入流加载到saxBuilder中
            Document document = saxBuilder.build(isr);
            // 4.通过document对象获取xml文件的根节点
            Element rootElement = document.getRootElement();
            // 5.获取根节点下的子节点的List集合
            List<Element> bookList = rootElement.getChildren();
            // 继续进行解析
            for (Element book : bookList) {
                Book bookEntity = new Book();
                System.out.println("======开始解析第" + (bookList.indexOf(book) + 1)
                        + "书======");
                // 解析book的属性集合
                List<Attribute> attrList = book.getAttributes();
                // //知道节点下属性名称时,获取节点值
                // book.getAttributeValue("id");
                // 遍历attrList(针对不清楚book节点下属性的名字及数量)
                for (Attribute attr : attrList) {
                    // 获取属性名
                    String attrName = attr.getName();
                    // 获取属性值
                    String attrValue = attr.getValue();
                    System.out.println("属性名:" + attrName + "----属性值:"
                            + attrValue);
                    if (attrName.equals("id")) {
                        bookEntity.setId(attrValue);
                    }
                }
                // 对book节点的子节点的节点名以及节点值的遍历
                List<Element> bookChilds = book.getChildren();
                for (Element child : bookChilds) {
                    System.out.println("节点名:" + child.getName() + "----节点值:"
                            + child.getValue());
                    if (child.getName().equals("name")) {
                        bookEntity.setName(child.getValue());
                    }
                    else if (child.getName().equals("author")) {
                        bookEntity.setAuthor(child.getValue());
                    }
                    else if (child.getName().equals("year")) {
                        bookEntity.setYear(child.getValue());
                    }
                    else if (child.getName().equals("price")) {
                        bookEntity.setPrice(child.getValue());
                    }
                    else if (child.getName().equals("language")) {
                        bookEntity.setLanguage(child.getValue());
                    }
                }
                System.out.println("======结束解析第" + (bookList.indexOf(book) + 1)
                        + "书======");
                booksList.add(bookEntity);
                bookEntity = null;
                System.out.println(booksList.size());
                System.out.println(booksList.get(0).getId());
                System.out.println(booksList.get(0).getName());
                
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. 方式四:DOM4J解析(推荐)


首先,需要两个jar包,dom4j和jaxen-1.1-beta-6.jar包。

在这里插入图片描述

package com.itholmes.xmlToJava;

import java.io.File;
import java.util.Iterator;
import java.util.List;

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

public class DOM4J {
	public static void main(String[] args) {
		// 创建SAXReader的对象reader
		SAXReader reader = new SAXReader();
		try {
			//通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
			Document document = reader.read(new File("src/resources/books.xml"));
			//通过document对象获取根节点rootElement
			Element rootElement = document.getRootElement();
			//通过rootElement对象的elementIterator方法获取迭代器
			Iterator<Element> elementIterator = rootElement.elementIterator();
			//遍历迭代器,获取根节点的内容
			while(elementIterator.hasNext()) {
				System.out.println("=====开始遍历某一本书=====");
				Element book = elementIterator.next();
				// 获取book的属性名以及 属性值
				List<Attribute> book_attrs_list = book.attributes();
				for (Attribute attr : book_attrs_list) {
                    System.out.println("属性名:" + attr.getName() + "--属性值:"
                            + attr.getValue());
                }
				
				Iterator itt = book.elementIterator();
                while (itt.hasNext()) {
                    Element bookChild = (Element) itt.next();
                    System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue());
                }
                System.out.println("=====结束遍历某一本书=====");
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

6. 使用DOM4J解析spring.xml文件,进而实现IOC容器和DI依赖注入

6.1 准备工作


为了完整实现,ioc容器的效果,这里我们创建两个实体类,方便创建xml的bean对象。

Dog类:

package com.itholmes.beans;

public class Dog {
	
	private String name;
	private int number;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	
}	

Person类:

package com.itholmes.beans;

public class Person {
	
	private String name;
	private int age;
	private Dog dog;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Dog getDog() {
		return dog;
	}
	public void setDog(Dog dog) {
		this.dog = dog;
	}
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", dog=" + dog + "]";
	}
	
}

创建一个Spring.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       ">
       
       <bean id="person1" class="com.itholmes.beans.Person">
       		<property name="name" value="张三"></property>
       		<property name="age" value="18"></property>
       		<property name="dog" ref="dog1"></property>
       </bean>
       <bean id="dog1" class="com.itholmes.beans.Dog">
       		<property name="name" value="旺财"></property>
       		<property name="number" value="3"></property>
       </bean>
</beans>

6.2 手写IOC容器和DI依赖注入的效果


这样我们只需要,通过java代码的方式来解析上面的spring.xml文件,从而放到一个ioc容器当中,并且给他注入值。

下面类中,我们的操作过程使用了大量的反射!!!

模拟一个ClassPathXmlApplicationContext类:

package com.itholmes;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.itholmes.beans.Person;

//实现IOC容器和DI的类
public class ClassPathXmlApplicationContext {
	
	Map<String,Object> ioc = new HashMap<String, Object>();
	
	public ClassPathXmlApplicationContext(String path) {
		
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(path);
			//拿到根元素beans标签中的内容,并且进行遍历
			Element rootElement = document.getRootElement();
			Iterator<Element> beans = rootElement.elementIterator();
			
			//这个while循环是为了创建对应的bean对象,然后按照id和bean对象,键值对的形式存到ioc(map)中。
			while(beans.hasNext()) {
				Element bean = beans.next();
				//获取属性id和class
				Attribute id_attribute = bean.attribute("id");
				Attribute class_attribute = bean.attribute("class");
				//获取分别属性id和class对应的值。
				String id_value = id_attribute.getValue();
				String class_value = class_attribute.getValue();
				
				//接下来就是将id属性对应的值 和 创建一个类路径为class_value的对象 , 进而存在map中。
				//创建对象,就是用反射来创建就可以了。
				Class<?> c = Class.forName(class_value);
				Object object = c.newInstance();
				ioc.put(id_value, object);
				
				System.out.println();
			}
			
			//注意这里我们之所以新创建一个beans2,而不用上面的beans就是因为迭代器的指针已经指向最后一个了。
			Iterator<Element> beans2 = rootElement.elementIterator();
			while(beans2.hasNext()) {
				
				Element bean = beans2.next();
				Attribute id_attribute = bean.attribute("id");
				//拿到bean的id的value值。
				String id_value = id_attribute.getValue();
				
				Iterator<Element> childs = bean.elementIterator();
				while(childs.hasNext()) {
					Element child = childs.next();
					String child_name = child.getName();
					if("property".equals(child_name)) {
						
						//拿到property每一个标签的属性
						Attribute name_attribute = child.attribute("name");
						Attribute value_attribute = child.attribute("value");
						
						//获取每一个属性的属性值。
						String name_value = name_attribute.getValue();
						
						//我们想要给对象注入值,就必须调用set方法也就是set注入,怎么获取set方法?还是通过反射。
						//首先,我们想将方法名拼接出来 set+首字母大写的name_value
						String methodName = getMethodName(name_value);
						
						//有了方法名,我们就可以在ioc中,通过id来拿到对象,同构反射来调用方法了。
						Object obj = ioc.get(id_value);
						
						//通过对象反射和方法名,获取到method。但是需要注意因为所有的set方法都是有参数的,这里我们也要传入参数!
						//并且我们还要判断参数的类型,因为从xml文件拿到的类型都是String类型
						Class<? extends Object> c = obj.getClass();
						
						//判断我们set方法注入的类型,就需要反射的field获取属性。
						Field field = c.getDeclaredField(name_value);
						Method method = c.getDeclaredMethod(methodName, field.getType());
						
						//不要忘记ref,这里是如果value属性对应的值为null,那说明用的是ref的属性。
						if(value_attribute!=null) {
							
							String value_value = value_attribute.getValue();
							
							Class<?> type = field.getType();
							Integer i = 0;
							if(type.toString().equals("int")) {
								if(value_value==null||value_value.equals("")) {
									value_value = "0";
								}
								i = Integer.parseInt(value_value);
								//对于int类型我们必须转换类型。当然如果还有其他类型必须在做判断
								Object invoke = method.invoke(obj, i);
							}else {
								//从而我们使用反射方法的三要素就可以调用set注入了。
								Object invoke = method.invoke(obj, value_value);
							}
							
						}else{
							Attribute ref_attribute = child.attribute("ref");
							String ref_value = ref_attribute.getValue();
							Object object = ioc.get(ref_value);
							
							Object invoke = method.invoke(obj, object);
							
						}
						System.out.println();
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	//模拟容器中的getBean方法
	public Object getBean(String id) {
		return ioc.get(id);
	}
	
	//通过拼接获取方法的名字也就是set+首字母大写的name_value
	public String getMethodName(String name) {
		String shouzimu = name.substring(0,1);
		String upperCase = shouzimu.toUpperCase();
		String result = "set"+upperCase+name.substring(1);
		return result;
	}
	
	//写一个main方法来测试一下。
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("src/resources/Spring.xml");
		Object person1 = ioc.getBean("person1");
		System.out.println();
	}
}

通过测试完美注入达到效果:
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xupengboo

你的鼓励将是我创作最大的动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值