­

手写spring IOC 框架

  • 2019 年 11 月 7 日
  • 笔记

什么是springICO?

就是把每一个bean(实体类) 与其他bean(实体类)的关系 交给第三方容器去管理

springICO底层实现原理?

1.读取bean的XML配置文件(读取配置文件)

2.使用beanId查找bean配置,并获取配置文件中class地址。

3.使用Java反射技术实例化对象

4.获取属性配置,使用反射技术进行赋值。

详细步骤

1.利用传入的参数获取xml文件的流,并且利用dom4j解析成Document对象

2.对于Document对象获取根元素对象<beans>后对下面的<bean>标签进行遍历,判断是否有符合的id.

3.如果找到对应的id,相当于找到了一个Element元素,开始创建对象,先获取class属性,根据属性值利用反射建立对象.

4.遍历<bean>标签下的property标签,并对属性赋值.

注意,需要单独处理int,float类型的属性.因为在xml配置中这些属性都是以字符串的形式来配置的,因此需要额外处理.

5.如果属性property标签有ref属性,说明某个属性的值是一个对象,那么根据id(ref属性的值)去获取ref对应的对象,再给属性赋值.

6.返回建立的对象,如果没有对应的id,或者<beans>下没有子标签都会返回null

环境准备:

XML

建好两个实体类 一个XML

package com.cheng.MavenTest;    import java.lang.reflect.Field;  import java.util.List;    import org.dom4j.Document;  import org.dom4j.Element;  import org.dom4j.io.SAXReader;    import com.cheng.entity.Tearchers;    public class Aplication {  	private String xmlPath;  	//配置文件  	public Aplication(String xmlPath){  		this.xmlPath=xmlPath;  	}  	//获取bean  	public Object getBeans(String beanId) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{  		//解析XML  		SAXReader xaxReader=new SAXReader();  		Document document=null;  		try {  			//从根目录下读取  			document=xaxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));      		} catch (Exception e) {  			e.printStackTrace();  		}  		//读取根节点信息  		Element element=document.getRootElement();  		//得到跟节点数组  		List<Element> list=element.elements();  		if (list.size()<=0){    			return null;  		}  		Object o=null;  		//遍历根节点  		for (Element element2 : list) {  			String id=element2.attributeValue("id");  			if(id.isEmpty()){    				return null;  			}  			if(!id.equals(beanId)){  				continue;    			}  			//获取类的路径  			String classBeans=element2.attributeValue("class");    			Class<?>  forName=Class.forName(classBeans);    			o=forName.newInstance();    			//赋值  			List<Element> list2=element2.elements();  			if(list2.size()<=0){    				return null;  			}  			for (Element element3 : list2) {  				String name=element3.attributeValue("name");  				String value=element3.attributeValue("value");  				Field file = forName.getDeclaredField(name);  				//设置允许访问私有变量  				file.setAccessible(true);  				file.set(o, value);  			}  		}  		return o;  	}  	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {  		Aplication aplication = new Aplication("SpringIOC.xml");    		Tearchers tearchers=(Tearchers) aplication.getBeans("tearChers");    		System.out.println(tearchers.getTearName());  		System.out.println(tearchers.getTrarAge());  	}  }

打印结果:

注意:需要单独处理int,float类型的属性.因为在xml配置中这些属性都是以字符串的形式来配置的,因此需要额外处理.

比如:我这里访问另外一个类

解决办法:

根据类型判断,这里只列出了 Integer 类型还有很多类型可以自己匹配!

另外这里只是注入属性,那么注入对象呢?

有什么问题可以在加QQ群:600922504

一起探讨技术。