用300行代码手写提炼Spring的核心原理(V2)

实现V2 版本

在V1 版本上进了优化,采用了常用的设计模式(工厂模式、单例模式、委派模式、策略模式),将init()方法中的代
码进行封装。按照之前的实现思路,先搭基础框架,再填肉注血,具体代码如下:

@Override
	public void init(ServletConfig config) throws ServletException {//初始化
		//加载配置文件
		doLoadConfig(config.getInitParameter("contextConfigLocation"));
		
		//2、扫描相关的类
		doScanner(contextConfig.getProperty("scanPackage"));

		//3、初始化扫描到的类,并且将它们放入到 ICO 容器之中
		doInstance();
		
		//4、完成依赖注入
		doAutowired();

		//5、初始化 initHandlerMapping
		initHandlerMapping();

		System.out.println("HZQ Spring framework is init.");
	}

声明全局的成员变量,其中IOC 容器就是注册时单例的具体案例:

	//新建一个“容器”
	private Map<String,Object> ioc = new HashMap<String, Object>();

	//保存 application.properties 配置文件中的内容
	private Properties contextConfig = new Properties();
	
	//保存扫描的所有的类名
	private List<String> classNames = new ArrayList<String>();

	//保存 url 和 Method 的对应关系
	private Map<String,Method> handlerMapping = new HashMap<String,Method>();

实现doLoadConfig()方法:

private void doLoadConfig(String initParameter) {
		//直接从类路径下找到 Spring 主配置文件所在的路径
		//并且将其读取出来放到 Properties 对象中
		//相对于 scanPackage=com.hezhiqin 从文件中保存到了内存中
		InputStream fis = this.getClass().getClassLoader().getResourceAsStream(initParameter);
		try {
			contextConfig.load(fis);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}

实现doScanner()方法:

/**
	 * @param scanPackage
	 * 扫描配置的路径,将所有相关的类放入容器中
	 */
	private void doScanner(String scanPackage) {
		//scanPackage = com.hezhiqin ,存储的是包路径
		//转换为文件路径,实际上就是把.替换为/就 OK 了
		URL url = this.getClass().getClassLoader().getResource("/" +
				scanPackage.replaceAll("\\.","/"));//将扫描的包的.换成/
		File classDir = new File(url.getFile());
		for (File file : classDir.listFiles()) {
			if (file.isDirectory()) {//如果是一个文件
				 doScanner(scanPackage + "." +file.getName());
			}else {
				if(!file.getName().endsWith(".class")){continue;}//不是一个class文件则跳过
				String clazzName = (scanPackage + "." + file.getName().replace(".class",""));//获取classpath
//				ioc.put(clazzName,null);//写入Key
//				System.out.println("ioc"+ioc);
				
				classNames.add(clazzName);//V2存到LIST中

			}
		}

		
	}

实现doInstance()方法,doInstance()方法就是工厂模式的具体实现:

/**
	*@Description: 初始化扫描到的类,并且将它们放入到 ICO 容器之中
	*@Param:
	*@return:
	*@Author: hezhiqin
	*@date: 2019/10/14
	*/
	private void doInstance() {
		if (classNames.isEmpty()) {
			return;
		}
		try {
			for (String className : classNames) {
				
				Class<?> clazz = Class.forName(className);//从Lits中存的类的地址获取内存中对应的Class
				//什么样的类才需要初始化呢?
				//加了注解的类,才初始化,怎么判断?
				//为了简化代码逻辑,主要体会设计思想,只举例 @Controller 和@Service,
				// @Componment...就不一举例了
				if (clazz.isAnnotationPresent(HZQController.class)) {//如果是@HZQControlle
					Object instance = clazz.newInstance();
					//Spring 默认类名首字母小写
					String beanName = toLowerFirstCase(clazz.getSimpleName());
					ioc.put(beanName,instance);//加载到容器中

				}else if (clazz.isAnnotationPresent(HZQService.class)) {
					//1、自定义的 beanName
					HZQService service = clazz.getAnnotation(HZQService.class);
					String beanName = service.value();
					if("".equals(beanName.trim())){
						beanName = toLowerFirstCase(clazz.getSimpleName());
					}
					Object instance = clazz.newInstance();
					ioc.put(beanName,instance);
					//3、根据类型自动赋值,投机取巧的方式
					for (Class<?> i  : clazz.getInterfaces()) {
						if (ioc.containsKey(i.getSimpleName())) {
							throw new Exception("The “" + i.getName() + "” is exists!!");
						}
						ioc.put(toLowerFirstCase(i.getSimpleName()), instance);
					}
				}else {
					continue;
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

为了处理方便,自己实现了toLowerFirstCase 方法,来实现类名首字母小写,具体代码如下:

private String toLowerFirstCase(String simpleName) {
		char [] chars = simpleName.toCharArray();
		//之所以加,是因为大小写字母的 ASCII 码相差 32,
		// 而且大写字母的 ASCII 码要小于小写字母的 ASCII 码
		//在 Java 中,对 char 做算学运算,实际上就是对 ASCII 码做算学运算
		if (isUpperCase(chars[0])) {
			chars[0] += 32;
		} 
		return String.valueOf(chars);

	}
/*
	 * 是否是大写
	 */
	public boolean isUpperCase(char c) {
	    return c >=65 && c <= 90;
	}

实现doAutowired()方法 ,其实就是注入的过程

private void doAutowired() {
		if(ioc.isEmpty()){return;}

		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			//Declared 所有的,特定的 字段,包括 private/protected/default
			//正常来说,普通的 OOP 编程只能拿到 public 的属性
			Field[] fields = entry.getValue().getClass().getDeclaredFields(); 
			for (Field field : fields) {
				if (!field.isAnnotationPresent(HZQAutowired.class)) {
					continue;
				}
				HZQAutowired autowired = field.getAnnotation(HZQAutowired.class);
				//如果用户没有自定义 beanName,默认就根据类型注入
				//这个地方省去了对类名首字母小写的情况的判断,这个作为课后作业
				//小伙伴们自己去完善
				String beanName = autowired.value().trim();
				if("".equals(beanName.trim())){
					beanName =toLowerFirstCase(field.getType().getSimpleName()) ;
				}
				
				//如果是 public 以外的修饰符,只要加了@Autowired 注解,都要强制赋值
				//反射中叫做暴力访问, 强吻
				field.setAccessible(true);
				try {
					//用反射机制,动态给字段赋值
					field.set(entry.getValue(),ioc.get(beanName));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}

			}
		}

	}

实现initHandlerMapping()方法,handlerMapping 就是策略模式的应用案例:

/**
	*@Description: 初始化 initHandlerMapping 将url访问地址和方法放入MAP中访问时进行调用
	*@Param: 
	*@return: 
	*@Author: hezhiqin
	*@date: 2019/10/14
	*/
	private void initHandlerMapping() {
		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			
			Class<?> clazz = entry.getValue().getClass();
			if(!clazz.isAnnotationPresent(HZQController.class)){continue;}
			//保存写在类上面的@HZQRequestMapping("/demo")
			String baseUrl = "";
			if(clazz.isAnnotationPresent(HZQRequestMapping.class)){
				HZQRequestMapping requestMapping = clazz.getAnnotation(HZQRequestMapping.class);
				baseUrl = requestMapping.value();
			}
			for (Method method : clazz.getMethods()) {
				if(!method.isAnnotationPresent(HZQRequestMapping.class)){continue;}
				HZQRequestMapping requestMapping = method.getAnnotation(HZQRequestMapping.class);
				String url = ("/" + baseUrl + "/" + requestMapping.value())
						.replaceAll("/+","/");
						handlerMapping.put(url,method);
						System.out.println("Mapped :" + url + "," + method);

			}


		}
		
	}

到这里位置初始化阶段就已经完成,接下实现运行阶段的逻辑,来看doPost/doGet 的代码:

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req,resp);
	}

	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			doDispatch(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));
		}

	}

doPost()方法中,用了委派模式,委派模式的具体逻辑在doDispatch()方法中:

private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String url = req.getRequestURI();//请求的相对路径
		System.out.println("url"+url);
		String contextPath = req.getContextPath();//项目根路径
		System.out.println("contextPath"+contextPath);
		url = url.replace(contextPath, "").replaceAll("/+", "/");
		System.out.println("url"+url);
//		if (!this.ioc.containsKey(url)) {//如果不存在这个路径则返回404
//			resp.getWriter().write("404 Not Found!!");
//			return;
//		}
//		Method method = (Method) this.ioc.get(url);
//        Map params = req.getParameterMap();
//        method.invoke(this.ioc.get(method.getDeclaringClass().getName()),new Object[]{req,resp,params.get("name")[0]});
		
		if ((!this.handlerMapping.containsKey(url))) {
			resp.getWriter().write("404 Not Found!!");
			return;
		}
		Method method = this.handlerMapping.get(url);
		
		//从 reqest 中拿到 url 传过来的参数
		Map<String,String[]> params = req.getParameterMap();
		
		//获取方法的形参列表
		//Class [] parameterTypes = method.getParameterTypes();
		Parameter[]  parameters  = method.getParameters();
		//保存赋值参数的位置
		Object [] paramValues = new Object[parameters.length];
		//按根据参数位置动态赋值
		for (int i = 0; i < parameters.length; i ++) {
			Parameter parameter = parameters[i];
			
			if(parameter.getType() == HttpServletRequest.class ){
				paramValues[i] = req;
				continue;

			}else if(parameter.getType()  == HttpServletResponse.class){
				paramValues[i] = resp;
				continue;
			}else if(parameter.getType()  == String.class){
				if (parameter.isAnnotationPresent(HZQRequestParam.class)) {
					HZQRequestParam requestParam = parameter.getAnnotation(HZQRequestParam.class);
					if(params.containsKey(requestParam.value())) {
						for (Map.Entry<String,String[]> param : params.entrySet()){
							String value = Arrays.toString(param.getValue())
									.replaceAll("\\[|\\]","")
									.replaceAll("\\s",",");
							paramValues[i] = value;

						}

					}
				}/*else {
					System.out.println(parameterType.getnam);
					if(params.containsKey(parameterType.getName())) {
						for (Map.Entry param : params.entrySet()){
							String value = Arrays.toString(param.getValue());
							paramValues[i] = value;
						}

					}
				}*/

			}



		}
		//投机取巧的方式
		//通过反射拿到 method 所在 class,拿到 class 之后还是拿到 class 的名称
		//再调用 toLowerFirstCase 获得 beanName
		String beanName= toLowerFirstCase(method.getDeclaringClass().getSimpleName());
		System.out.println(ioc.get(beanName));
		method.invoke(ioc.get(beanName),paramValues);
		
	}

整个代码:

package com.hezhiqin.mvcframwork.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hezhiqin.hand.HandlerMapping;
import com.hezhiqin.mvcframework.annotation.HZQAutowired;
import com.hezhiqin.mvcframework.annotation.HZQController;
import com.hezhiqin.mvcframework.annotation.HZQRequestMapping;
import com.hezhiqin.mvcframework.annotation.HZQRequestParam;
import com.hezhiqin.mvcframework.annotation.HZQService;

/**
 * @author Administrator
 *所有的核心逻辑卸载init方法中
 */
public class HZQDispathcherServlet  extends HttpServlet{
	
	//新建一个“容器”
	private Map<String,Object> ioc = new HashMap<String, Object>();

	//保存 application.properties 配置文件中的内容
	private Properties contextConfig = new Properties();
	
	//保存扫描的所有的类名
	private List<String> classNames = new ArrayList<String>();

	//保存 url 和 Method 的对应关系
//	private Map handlerMapping = new HashMap();
	
	private List<HandlerMapping> handlerMapping = new ArrayList<HandlerMapping>();



	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req,resp);
	}

	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			doDispatch(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));
		}

	}



	private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		 HandlerMapping handler = getHandler(req);
		 if (handler==null) {
			 resp.getWriter().write("404 Not Found!!!");
			 return;

		}
		 
		//获得方法的形参列表
		 Class<?> [] paramTypes = handler.getParamTypes();
		 
		 Object [] paramValues = new Object[paramTypes.length];

		 Map<String,String[]> params = req.getParameterMap();
		 
		 for (Map.Entry<String, String[]> parm : params.entrySet()) {
			 
			 String value = Arrays.toString(parm.getValue()).replaceAll("\\[|\\]","")
					 .replaceAll("\\s",",");
			 if(!handler.paramIndexMapping.containsKey(parm.getKey())){continue;}
			 int index = handler.paramIndexMapping.get(parm.getKey());
			 paramValues[index] = convert(paramTypes[index],value);


			 
		 }
		 
		 if(handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
			 int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
			 paramValues[reqIndex] = req;
		 }



		 if(handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
			 int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
			 paramValues[respIndex] = resp;
		 }
		 
		 Object returnValue = handler.method.invoke(handler.controller,paramValues);
		 
		 if(returnValue == null || returnValue instanceof Void){ return; }
		 
		 resp.getWriter().write(returnValue.toString());




		
	}



	private HandlerMapping getHandler(HttpServletRequest req) {
		if(handlerMapping.isEmpty()){ return null; }
		String url = req.getRequestURI();
		String contextPath = req.getContextPath();
		url = url.replace(contextPath, "").replaceAll("/+", "/");
		System.out.println("我草拟大爷"+url);
		for (HandlerMapping  handler : handlerMapping) {
			Matcher matcher = handler.pattern.matcher(url);
			System.out.println(matcher.matches());
			//如果没有匹配上继续下一个匹配
			if(!matcher.matches()){ continue; }
			return handler;
		}
		return null;
		

	}



	@Override
	public void init(ServletConfig config) throws ServletException {//初始化
		//加载配置文件
		doLoadConfig(config.getInitParameter("contextConfigLocation"));
		
		//2、扫描相关的类
		doScanner(contextConfig.getProperty("scanPackage"));

		//3、初始化扫描到的类,并且将它们放入到 ICO 容器之中
		doInstance();
		
		//4、完成依赖注入
		doAutowired();

		//5、初始化 initHandlerMapping
		initHandlerMapping();

		System.out.println("HZQ Spring framework is init.");
		
		
	}



	private void initHandlerMapping() {
		if(ioc.isEmpty()){ return; }
		for (Entry<String, Object> entry : ioc.entrySet()) {
			Class<?> clazz = entry.getValue().getClass();
			if(!clazz.isAnnotationPresent(HZQController.class)){ continue; }
			String url = "";
			if(clazz.isAnnotationPresent(HZQRequestMapping.class)){
				HZQRequestMapping requestMapping = clazz.getAnnotation(HZQRequestMapping.class);
				url = requestMapping.value();
			}
			
			//获取 Method 的 url 配置
			Method [] methods = clazz.getMethods();
			
			for (Method method : methods) {
				
				//没有加 RequestMapping 注解的直接忽略
				if(!method.isAnnotationPresent(HZQRequestMapping.class)){ continue; }
				//映射 URL
				HZQRequestMapping requestMapping = method.getAnnotation(HZQRequestMapping.class);
				String regex = ("/" + url + requestMapping.value()).replaceAll("/+", "/");
				Pattern pattern = Pattern.compile(regex);
				handlerMapping.add(new HandlerMapping(entry.getValue(),method,pattern));
				System.out.println("mapping " + regex + "," + method);

			}



		}

		
	}



	private void doAutowired() {
		if(ioc.isEmpty()){return;}

		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			//Declared 所有的,特定的 字段,包括 private/protected/default
			//正常来说,普通的 OOP 编程只能拿到 public 的属性
			Field[] fields = entry.getValue().getClass().getDeclaredFields(); 
			for (Field field : fields) {
				if (!field.isAnnotationPresent(HZQAutowired.class)) {
					continue;
				}
				HZQAutowired autowired = field.getAnnotation(HZQAutowired.class);
				//如果用户没有自定义 beanName,默认就根据类型注入
				//这个地方省去了对类名首字母小写的情况的判断,这个作为课后作业
				//小伙伴们自己去完善
				String beanName = autowired.value().trim();
				if("".equals(beanName.trim())){
					beanName =toLowerFirstCase(field.getType().getSimpleName()) ;
				}
				
				//如果是 public 以外的修饰符,只要加了@Autowired 注解,都要强制赋值
				//反射中叫做暴力访问, 强吻
				field.setAccessible(true);
				try {
					//用反射机制,动态给字段赋值
					field.set(entry.getValue(),ioc.get(beanName));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}

			}
		}

	}



	private void doInstance() {
		if (classNames.isEmpty()) {
			return;
		}
		try {
			for (String className : classNames) {
				
				Class<?> clazz = Class.forName(className);//从Lits中存的类的地址获取内存中对应的Class
				//什么样的类才需要初始化呢?
				//加了注解的类,才初始化,怎么判断?
				//为了简化代码逻辑,主要体会设计思想,只举例 @Controller 和@Service,
				// @Componment...就不一举例了
				if (clazz.isAnnotationPresent(HZQController.class)) {//如果是@HZQControlle
					Object instance = clazz.newInstance();
					//Spring 默认类名首字母小写
					String beanName = toLowerFirstCase(clazz.getSimpleName());
					ioc.put(beanName,instance);//加载到容器中

				}else if (clazz.isAnnotationPresent(HZQService.class)) {
					//1、自定义的 beanName
					HZQService service = clazz.getAnnotation(HZQService.class);
					String beanName = service.value();
					if("".equals(beanName.trim())){
						beanName = toLowerFirstCase(clazz.getSimpleName());
					}
					Object instance = clazz.newInstance();
					ioc.put(beanName,instance);
					//3、根据类型自动赋值,投机取巧的方式
					for (Class<?> i  : clazz.getInterfaces()) {
						if (ioc.containsKey(i.getSimpleName())) {
							throw new Exception("The “" + i.getName() + "” is exists!!");
						}
						ioc.put(toLowerFirstCase(i.getSimpleName()), instance);
					}
				}else {
					continue;
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	private void doLoadConfig(String initParameter) {
		//直接从类路径下找到 Spring 主配置文件所在的路径
		//并且将其读取出来放到 Properties 对象中
		//相对于 scanPackage=com.hezhiqin 从文件中保存到了内存中
		InputStream fis = this.getClass().getClassLoader().getResourceAsStream(initParameter);
		try {
			contextConfig.load(fis);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}



	/**
	 * @param scanPackage
	 * 扫描配置的路径,将所有相关的类放入容器中
	 */
	private void doScanner(String scanPackage) {
		//scanPackage = com.hezhiqin ,存储的是包路径
		//转换为文件路径,实际上就是把.替换为/就 OK 了
		URL url = this.getClass().getClassLoader().getResource("/" +
				scanPackage.replaceAll("\\.","/"));//将扫描的包的.换成/
		File classDir = new File(url.getFile());
		for (File file : classDir.listFiles()) {
			if (file.isDirectory()) {//如果是一个文件
				 doScanner(scanPackage + "." +file.getName());
			}else {
				if(!file.getName().endsWith(".class")){continue;}//不是一个class文件则跳过
				String clazzName = (scanPackage + "." + file.getName().replace(".class",""));//获取classpath
//				ioc.put(clazzName,null);//写入Key
//				System.out.println("ioc"+ioc);
				
				classNames.add(clazzName);//V2存到LIST中

			}
		}

		
	}
	
	
	private String toLowerFirstCase(String simpleName) {
		char [] chars = simpleName.toCharArray();
		//之所以加,是因为大小写字母的 ASCII 码相差 32,
		// 而且大写字母的 ASCII 码要小于小写字母的 ASCII 码
		//在 Java 中,对 char 做算学运算,实际上就是对 ASCII 码做算学运算
		if (isUpperCase(chars[0])) {
			chars[0] += 32;
		} 
		return String.valueOf(chars);

	}
	
	

	/*
	 * 是否是大写
	 */
	public boolean isUpperCase(char c) {
	    return c >=65 && c <= 90;
	}
	
	
	private Object convert(Class<?> type,String value){
		if(Integer.class == type){
			return Integer.valueOf(value);
		}
		return value;
	}

	
}

你可能感兴趣的:(Spring源码剖析,Spring)