数据交换格式与SpringIOC底层实现

一:什么是数据交换格式:

json,xml
二:各自应用场景?
json:是一种轻量级的数据交换格式。http+restful
xml:是一种重量级的数据交换格式(标记语言)

面向服务架构(soa)或者为服务架构--http+json格式

三:json与xml区别?
1.json占宽带小,xml占宽带大。
2.微服务http+json格式
3.配置文件,webService(http+soap协议)http+xml进行传输
常用于银行,银行的内部接口xml,maven配置。

四:json

jsonObject--json对象
jsonarray---json数组
{
"id":"29",
"name":"须臾",
"items":[{
"itemId":"22",
"itemName":"哈哈"
}]
}
java操作json有哪些框架?
gson(谷歌),fastjson(阿里巴巴)--主流,jackson(springmvc)

五:json转化为对象
User user =
 new JSONObject().parseObject(json, User.class);

六:什么是xml?
可扩展标记语言 描述数据 配置文件。
zookeeper类似节点方式存储
xml存储结构类似于树状存储结构。
解析xml方式 有哪些?
Dom4j,SAX,pull
Dom4j与SAX区别?
1.dom4j不适合大文件解析,因为一下子将文件加载到内存中,
有可能出现内存溢出。
2.SAX解析大型xml文件,SAX基于事件对xml解析

七:什么是Java的反射机制?(非常重要)
框架,jdbc连接,springIoc
反射机制就是正在运行动态获取当前的类的所有信息。
类可以不用new,使用Java的反射机制 帮你去初始化。
类的私有属性,可以使用Java的反射机制赋值。
核心当前类的class文件。

--反射机制作用--
提高程序的扩展性,封装一些工具类,写框架。

怎么禁止Java的反射机制?
把对象的构造函数改为private。

Java反射机制应用?
springIoc jdbc


八:SpringIOC控制反转--将每个bean与bean之间的关系交给
第三方容器(Spring)进行管理


解析json:
package com.xss;

import com.alibaba.fastjson.JSONObject;
import com.xss.entity.User;

public class Test001 {
	// 定义了一个json字符串
	static String json = "{\"id\":\"20\",\"name\":\"君君\",\"items\":[{\"itemId\":\"21\",\"itemName\":\"IT教育\"},{\"itemId\":\"21\",\"itemName\":\"IY课堂\"}]}";

	public static void main(String[] args) {
		// 1.先转换成jsonobject对象
//		JSONObject jsonObject = new JSONObject().parseObject(json);
//		// String id=(String) jsonObject.get("id");
//		String id = jsonObject.getString("id");
//		String name = jsonObject.getString("name");
//		System.out.println("id:" + id + "--name" + name);
//		
//		//解析json数组
//		JSONArray jsonArray = jsonObject.getJSONArray("items");
//		for (int i = 0; i < jsonArray.size(); i++) {
//			JSONObject object = jsonArray.getJSONObject(i);
//			String itemId = object.getString("itemId");
//			String itemName = object.getString("itemName");
//			System.out.println("itemId:" + itemId + "--itemName" + itemName);
//			// JSONObject object=(JSONObject) jsonArray.get(i);
//
//		}
	//json转换对象
		User user = new JSONObject().parseObject(json,User.class);
		System.out.println(user.toString());
	}

}

测试结果:
无参构造函数-使用Java的反射机制创建user对象
User [id=20, name=君君, items=[Item [itemId=21, itemName=IT教育], Item [itemId=21, itemName=IY课堂]]]

package com.xss;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;

public class Test002 {

	public static void main(String[] args) {
		
//		JSONObject jsonObject = new JSONObject();
//		JSONObject root = jsonObject;
//		root.put("id", "20");
//		root.put("name", "须臾");
//		//json数组
//		JSONArray jsonArray = new JSONArray();
//		//jso数组里的对象
//		JSONObject jsonObject2 = new JSONObject();
//		jsonObject2.put("itemId", "20");
//		jsonObject2.put("itemName", "IT学院");
//		JSONObject jsonObject3=new JSONObject();
//		jsonObject3.put("itemId", "21");
//		jsonObject3.put("itemName", "阿三");
//		jsonArray.add(jsonObject2);
//		jsonArray.add(jsonObject3);
//		root.put("items", jsonArray);
//		System.out.println(root.toJSONString());
		//使用实体类封装json字符串
		User user = new User();
		user.setId("20");
		user.setName("修十九世纪");
		List<Item> arrayList = new ArrayList<Item>();
		Item item = new Item();
		item.setItemId("23");
		item.setItemName("时代的");
		Item item1 = new Item();
		item1.setItemId("23");
		item1.setItemName("时代的");
		arrayList.add(item);
		arrayList.add(item1);
		user.setItems(arrayList);
		System.out.println(new JSONObject().toJSONString(user));
	}
}
无参构造函数-使用Java的反射机制创建user对象
{"id":"20","items":[{"itemId":"23","itemName":"时代的"},{"itemId":"23","itemName":"时代的"}],"name":"修十九世纪"}

解析xml:

package com.xss;

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 Test003 {
	public static void main(String[] args) throws DocumentException {
		//1.获取到读取对象
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read("f:\\student.xml");
		Element rootElement = document.getRootElement();
		getNodes(rootElement);
	}
	static public void getNodes(Element rootElement){
		String name = rootElement.getName();
		System.out.println("节点名称:"+name);
		//获取节点属性
		List<Attribute> attributes = rootElement.attributes();
		for (Attribute attribute : attributes) {
			System.out.println("属性名称:"+attribute.getName()+",属性value"+attribute.getValue());
		}
		String value=rootElement.getTextTrim();
		if(!value.equals("")){
			System.out.println("节点value"+value);
		}
		//判断是否有下一个节点
		Iterator<Element> elementIterator = rootElement.elementIterator();
		while (elementIterator.hasNext()) {
			Element next = elementIterator.next();
			getNodes(next);
		}
	}
}

手写spring IOC框架:

实体类:

package com.xuyuedu.entity;

public class UserEntity {
	private String userId;
	private String userName;

	 public UserEntity(){
		 System.out.println("无参构造函数....");
	 }
	
	public String getUserId() {

		return userId;
	}

	public void setUserId(String userId) {

		this.userId = userId;
	}

	public String getUserName() {

		return userName;
	}

	public void setUserName(String userName) {

		this.userName = userName;
	}

	@Override
	public String toString() {
		return "UserEntity [userId=" + userId + ", userName=" + userName + "]";
	}

}
反射解析:
package com.xuyuedu.test;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.xuyuedu.entity.UserEntity;

public class ClassPathXmlApplicationContext {
	private static String PATH;
	private static String ID;
	private static String CLASS;
	private static String NAME;
	private static String VALUE;

	public void init() {
		ID = "id";
		CLASS = "class";
		NAME = "name";
		VALUE = "value";
	}

	public ClassPathXmlApplicationContext(String path) {
		init();
		// 获取spring读取文件名称
		this.PATH = path;
	}

	public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, InstantiationException,
			IllegalAccessException, NoSuchFieldException, SecurityException {
		// 1、解析xml
		if (StringUtils.isEmpty(beanId)) {
			return null;
		}
		SAXReader saxReader = new SAXReader();
		Document read = saxReader.read(this.getClass().getClassLoader().getResource(PATH));
		//获取根节点【beans】
		Element rootElement = read.getRootElement();
		//获得根节点下的所有子节点【bean】
		List<Element> elements = rootElement.elements();
		//遍历子节点
		for (Element element : elements) {
			//找到Id
			String id = element.attributeValue(ID);
			if (!beanId.equals(id)) {
				// 结束本次循环
				continue;
			}
			// 2、使用beanid查找对应xml节点,获取class节点属性
			// 从配置文件中获取bean【class】
			String attClass = element.attributeValue(CLASS);
			// 3、使用java的反射机制初始化类
			Class<?> forName = Class.forName(attClass);
			//反射调用有参函数
			Object newInstance = forName.newInstance();
			// 4、获取属性【properties】
			List<Element> sonEle = element.elements();
			//遍历属性下的name,value
			for (Element el : sonEle) {
				// 获取配置文件属性名称
				String attField = el.attributeValue(NAME);
				String attFieldValue = el.attributeValue(VALUE);
				//获得私有属性
				Field declaredField = forName.getDeclaredField(attField);
				//暴力反射获取私有属性
				declaredField.setAccessible(true);
				//给有参构造函数赋值【value】
				declaredField.set(newInstance, attFieldValue);
			}
			return newInstance;
		}
		return null;

	}

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
			IllegalAccessException, NoSuchFieldException, SecurityException, DocumentException {
		ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserEntity user = (UserEntity) app.getBean("user2");
		System.out.println(user.toString());
	}

}

测试结果:

无参构造函数....
UserEntity [userId=0003, userName=腾讯课堂]

 
 

猜你喜欢

转载自blog.csdn.net/qq_38357267/article/details/80990139