1、什么是springIOC
IOC就是把每一个bean(实体类)与bean(实体了)之间的关系交给第三方容器进行管理。
如果我们手写一个最最简单的IOC,最终效果是怎样呢?
xml配置:
java代码:
//1.读取springxml配置
ClassPathXmlApplicationContext classPathXmlApplicationContext = newClassPathXmlApplicationContext("applicationContext.xml");//2.获取bean对象
TestService testService = (TestService) classPathXmlApplicationContext.getBean("testService");
System.out.println(testService.test());
2、什么是springIOC底层实现原理
1.读取bean的XML配置文件
2.使用beanId查找bean配置,并获取配置文件中class地址。
3.使用Java反射技术实例化对象
4.获取属性配置,使用反射技术进行赋值。
3、详细步骤
1.利用传入的参数获取xml文件的流,并且利用dom4j解析成Document对象
2.对于Document对象获取根元素对象后对下面的标签进行遍历,判断是否有符合的id.
3.如果找到对应的id,相当于找到了一个Element元素,开始创建对象,先获取class属性,根据属性值利用反射建立对象.
4.遍历标签下的property标签,并对属性赋值.注意,需要单独处理int,float类型的属性.因为在xml配置中这些属性都是以字符串的形式来配置的,因此需要额外处理.
5.如果属性property标签有ref属性,说明某个属性的值是一个对象,那么根据id(ref属性的值)去获取ref对应的对象,再给属性赋值.
6.返回建立的对象,如果没有对应的id,或者下没有子标签都会返回null
3.1、建立实体类
public classUser {privateString userId;privateString userName;publicString getUserId() {returnuserId;
}public voidsetUserId(String userId) {this.userId =userId;
}publicString getUserName() {returnuserName;
}public voidsetUserName(String userName) {this.userName =userName;
}
}
3.2、使用反射技术完成java代码
public classClassPathXmlApplicationContext {private String pathXml = null;publicClassPathXmlApplicationContext(String pathXml) {this.pathXml =pathXml;
}public Object getBean(String beanId) throwsException {if(StringUtils.isEmpty(beanId)) {throw new Exception("beanId is null");
}
SAXReader saxReader= newSAXReader();
Document read= saxReader.read(this.getClass().getClassLoader().getResource(pathXml));//获取到根节点
Element rootElement =read.getRootElement();//根节点下所有的子节点
List elements =rootElement.elements();for(Element element : elements) {//获取到节点上的属性
String id = element.attributeValue("id");if(StringUtils.isEmpty(id)) {continue;
}if (!id.equals(beanId)) {continue;
}//使用java反射机制初始化对象
String beanClass = element.attributeValue("class");
Class> forName =Class.forName(beanClass);
Object newInstance=forName.newInstance();
List propertyElementList =element.elements();for(Element el : propertyElementList) {
String name= el.attributeValue("name");
String value= el.attributeValue("value");
Field declaredField=forName.getDeclaredField(name);
declaredField.setAccessible(true);
declaredField.set(newInstance, value);
}returnnewInstance;
}return null;
}}
3.3、测试
public static void main(String[] args) throwsException {
ClassPathXmlApplicationContext classPath= new ClassPathXmlApplicationContext("applicationContext.xml");
User user= (User) classPath.getBean("user2");
System.out.println(user.getUserId()+ "---" +user.getUserName());
}