[Spring] 30个类手写 Spring Mini 版本系列(一)

2023-12-22 01:32

本文主要是介绍[Spring] 30个类手写 Spring Mini 版本系列(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[Spring] 30个类手写 Spring Mini 版本系列(一)

简介

为了更深入的了解 Spring 的实现原理和设计思想,一直打算出个系列文章,从零开始重新学习 Spring。有兴趣的小伙伴可以持续关注更新。


目录

  • [Spring] 30个类手写 Spring Mini 版本系列(一)
    • V1 版本
      • V1.0.0 版本
        • 注解定义
        • 定义 Controller 和 Service
        • 定义配置
        • 定义 DispatchServlet
        • 效果演示
        • 小结
    • 更多

手机用户请横屏获取最佳阅读体验,REFERENCES中是本文参考的链接,如需要链接和更多资源,可以关注其他博客发布地址。

平台地址
CSDNhttps://blog.csdn.net/sinat_28690417
简书https://www.jianshu.com/u/3032cc862300
个人博客https://yiyuer.github.io/NoteBooks/

正文


基本思路

  • 配置阶段
    • 配置 web.xml
      • DispatchSevlet
    • 设定 init-param
      • contextConfigLocation = classpath:application.xml
    • 设定url-pattern
      • /*
    • 定义Annotation
      • @Controller
      • @Service
      • @Autowried
      • @RequestMapping
  • 初始化阶段
    • 调用 init() 方法
      • 加载配置文件
    • IOC容器初始化
      • Map<String,Object>
    • 扫描相关的类
      • Scan-package=“com.yido”
    • 创建实例化并保存至容器
      • 通过反射机制将类实例化放入 IOC 容器
    • 进行 DI
      • 扫描 IOC 容器中的实例,给没有赋值的属性自动赋值
    • 初始化 HandlerMapping
      • 将 URL 和 Method 建立一对一的映射关系
  • 运行阶段
    • 调用 doPost() / doGet()
      • Web 容器调用 doPost() / doGet() ,获得 request / response 对象
    • 匹配 HandlerMapping
      • 从 request 对象中获取用户输入的 url , 找到对应的 Method
    • 反射调用 method.invoke()
      • 利用反射调用方法并返回结果
    • 返回结果
      • 利用 response.getWriter().write(), 将返回结果输出到浏览器

V1 版本

准备工作

> pom.xml

  • sevlet-api 依赖
  • jetty 插件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><artifactId>yido-spring-v1</artifactId><packaging>war</packaging><!--此处由于本地开发用的是多模块,所以如果单独项目,不用配置该节点--><parent><groupId>com.yido</groupId><artifactId>yido-study</artifactId><version>1.0.0</version></parent><properties></properties><dependencies><!-- requied start --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId></dependency><!-- requied end --></dependencies><build><finalName>${artifactId}</finalName><resources><resource><directory>${basedir}/src/main/resources</directory><includes><include>**/*</include></includes></resource><resource><directory>${basedir}/src/main/java</directory><excludes><exclude>**/*.java</exclude><exclude>**/*.class</exclude></excludes></resource></resources><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>2.3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding><compilerArguments><verbose /><bootclasspath>${java.home}/lib/rt.jar</bootclasspath></compilerArguments></configuration></plugin><plugin><artifactId>maven-resources-plugin</artifactId><version>2.5</version><executions><execution><id>copy-resources</id><!-- here the phase you need --><phase>validate</phase><goals><goal>copy-resources</goal></goals><configuration><encoding>UTF-8</encoding><outputDirectory>${basedir}/target/classes</outputDirectory><resources><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes><filtering>true</filtering></resource></resources></configuration></execution></executions></plugin><plugin><groupId>org.mortbay.jetty</groupId><artifactId>maven-jetty-plugin</artifactId><version>6.1.26</version><configuration><webDefaultXml>src/main/resources/webdefault.xml</webDefaultXml><contextPath>/</contextPath><connectors><connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"><port>8080</port></connector></connectors><scanIntervalSeconds>0</scanIntervalSeconds><scanTargetPatterns><scanTargetPattern><directory>src/main/webapp</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></scanTargetPattern></scanTargetPatterns><systemProperties><systemProperty><name>javax.xml.parsers.DocumentBuilderFactory</name><value>com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl</value></systemProperty><systemProperty><name>javax.xml.parsers.SAXParserFactory</name><value>com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl</value></systemProperty><systemProperty><name>javax.xml.transform.TransformerFactory</name><value>com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl</value></systemProperty><systemProperty><name>org.eclipse.jetty.util.URI.charset</name><value>UTF-8</value></systemProperty></systemProperties></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.2</version><configuration><archive><addMavenDescriptor>false</addMavenDescriptor></archive><webResources><resource><!-- this is relative to the pom.xml directory --><directory>src/main/resources/</directory><targetPath>WEB-INF/classes</targetPath><includes><include>**/*.*</include></includes><!-- <excludes><exclude>**/local</exclude><exclude>**/test</exclude><exclude>**/product</exclude></excludes> --><filtering>true</filtering></resource><resource><!-- this is relative to the pom.xml directory --><directory>src/main/resources</directory><targetPath>WEB-INF/classes</targetPath><filtering>true</filtering></resource></webResources></configuration></plugin><plugin><groupId>org.zeroturnaround</groupId><artifactId>javarebel-maven-plugin</artifactId><executions><execution><id>generate-rebel-xml</id><phase>process-resources</phase><goals><goal>generate</goal></goals></execution></executions><version>1.0.5</version></plugin></plugins></build>
</project>

> web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4"><display-name>Sun Web Application</display-name><!--定义核心调度 servlet --><servlet><servlet-name>mvc-servlet</servlet-name><servlet-class>com.yido.mvcframework.v1.servlet.XDispatchServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>application.properties</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc-servlet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping><!--直接通过 servlet api 使用--><servlet><servlet-name>sun-servlet</servlet-name><servlet-class>com.yido.simple.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>sun-servlet</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping>
</web-app>

V1.0.0 版本

注解定义

.

定义 Controller 和 Service

.

定义配置
  • src/main/resources/application.properties
scanPackage=com.yido.demo
  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4"><display-name>Sun Web Application</display-name><!--定义核心调度 servlet --><servlet><servlet-name>mvc-servlet</servlet-name><servlet-class>com.yido.mvcframework.v1.servlet.XDispatchServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>application.properties</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc-servlet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping><!--直接通过 servlet api 使用--><servlet><servlet-name>sun-servlet</servlet-name><servlet-class>com.yido.simple.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>sun-servlet</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping>
</web-app>
定义 DispatchServlet
/** @ProjectName: 编程学习* @Copyright:   2019 HangZhou Ashe Dev, Ltd. All Right Reserved.* @address:     https://yiyuery.github.io/NoteBooks/* @date:        2020/4/12 5:30 下午* @description: 本内容仅限于编程技术学习使用,转发请注明出处.*/
package com.yido.mvcframework.v1.servlet;import com.yido.mvcframework.annotation.XAutowired;
import com.yido.mvcframework.annotation.XController;
import com.yido.mvcframework.annotation.XRequestMapping;
import com.yido.mvcframework.annotation.XService;import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;/*** <p>* 手写一个 请求转发器 DispatchServlet* </p>** @author Helios* @date 2020/4/12 5:30 下午*/
public class XDispatchServlet extends HttpServlet {/*** key: 请求路由* value:* - 对应 Controller 实例* - Method 方法*/private Map<String, Object> mapping = new HashMap<String, Object>();/*** Get 请求处理转发** @param req* @param resp* @throws ServletException* @throws IOException*/@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}/*** Post请求处理转发** @param req* @param resp* @throws ServletException* @throws IOException*/@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {try {doDispatch(req, resp);} catch (Exception e) {//出现异常,返回堆栈信息resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));}}/*** 统一转发处理所有请求数据** @param req* @param resp* @throws ServletException* @throws IOException*/private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {//1. 获取参数和请求路径String url = req.getRequestURI();String contextPath = req.getContextPath();//替换请求上下文url = url.replace(contextPath, "")//替换多余 '/'.replaceAll("/+", "/");// 2. 获取请求处理器/*** {@link XDispatchServlet#init(ServletConfig)}* 从缓存的 requestMapping 中加载指定包路径下的请求路径对应的 Controller 处理器* - 配置 web.xml* - 初始化时 加载配置文件*/if (!this.mapping.containsKey(url)) {resp.getWriter().write("404 Not Found!");return;}Method method = (Method) this.mapping.get(url);// 3. 解析参数并通过反射执行方法Map<String, String[]> parameterMap = req.getParameterMap();Object controller = this.mapping.get(method.getDeclaringClass().getName());method.invoke(controller, new Object[]{req, resp, parameterMap.get("name")[0]});}/*** 加载配置并缓存 Controller 实例和 初始化请求对应的 Method映射** @param config* @throws ServletException*/@Overridepublic void init(ServletConfig config) throws ServletException {InputStream is = null;try {//1. 读取参数Properties configContext = new Properties();is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));configContext.load(is);//2. IOC 构建容器, 扫描所有实例和请求方法映射doIoc(configContext.getProperty("scanPackage"));//3. DI 依赖注入doInjection();} catch (Exception e){e.printStackTrace();} finally {if (is != null) {try{is.close();} catch (IOException e) {e.printStackTrace();}}}System.out.println("XSpring MVC Framework has been initialed");}/*** 依赖注入*/private void doInjection() {Collection<Object> values = mapping.values();for (Object value : values) {if (null == value) {continue;}Class clazz = value.getClass();if (clazz.isAnnotationPresent(XController.class)) {Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {if (!field.isAnnotationPresent(XAutowired.class)) {continue;}XAutowired autowired = field.getAnnotation(XAutowired.class);String beanName = autowired.value();if ("".equals(beanName)) {beanName = field.getType().getName();}//注入依赖实例field.setAccessible(true);try {field.set(value, mapping.get(beanName));} catch (IllegalAccessException e) {e.printStackTrace();}}}}}/*** IOC 加载所有请求处理方法映射和实例*/private void doIoc(String scanPackage) throws ClassNotFoundException, IllegalAccessException, InstantiationException {doScanTask(scanPackage);Map<String, Object> cacheMap = new HashMap<String, Object>();for (String clazzName : mapping.keySet()) {if (!clazzName.contains(".")) {continue;}Class<?> clazz = Class.forName(clazzName);// 1. 处理 XControllerString baseUrl = "";if (clazz.isAnnotationPresent(XController.class)) {cacheMap.put(clazzName, clazz.newInstance());// 1.1 解析请求路径前缀if (clazz.isAnnotationPresent(XRequestMapping.class)) {XRequestMapping requestMapping = clazz.getAnnotation(XRequestMapping.class);baseUrl = requestMapping.value();}// 1.2 解析方法Method[] methods = clazz.getDeclaredMethods();for (Method method : methods) {if (method.isAnnotationPresent(XRequestMapping.class)) {XRequestMapping annotation = method.getAnnotation(XRequestMapping.class);String url = baseUrl + annotation.value();cacheMap.put(url, method);System.out.println("> Mapped--------->url: " + url + "," + method.getName());}}// 2. 处理 XService} else if (clazz.isAnnotationPresent(XService.class)) {XService service = clazz.getAnnotation(XService.class);String beanName = service.value();if ("".equals(beanName)) {beanName = clazzName.getClass().getName();}Object instance = clazz.newInstance();cacheMap.put(beanName, instance);for (Class<?> i : clazz.getInterfaces()) {cacheMap.put(i.getName(),instance);}}}if (!cacheMap.isEmpty()) {this.mapping.putAll(cacheMap);}}/*** 扫描指定包路径下所有需实例类* @param scanPackage*/private void doScanTask(String scanPackage) {URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));File rootDir = new File(url.getFile());for (File file : rootDir.listFiles()) {if (file.isDirectory()) {doScanTask(scanPackage+"."+file.getName());}else{if (!file.getName().endsWith(".class")) {continue;}String clazzName = scanPackage + "." + file.getName().replace(".class", "");mapping.put(clazzName, null);}}}
}
效果演示
/*** 返回欢迎信息* support:*  spring-v1* @param name*/@XRequestMapping("/v1/welcome")public void welcome(HttpServletRequest req, HttpServletResponse resp, @XRequestParam(value = "name") String name) {String result = helloService.welcome(name);try {resp.getWriter().write(result);} catch (IOException e) {e.printStackTrace();}}

.

小结
  • XDispatchServlet 职责不够单一
  • 流程方法混乱,不清晰
  • XDispatchServlet 需要进行重构
  • 没有自动解析注入 Request 、Response 对象
  • Spring 思想没有体现,没有 ApplicationContext、BeanDefinition、BeanDefinitionReader,没有解决循环依赖问题
  • 没有 Aop 逻辑
  • To do Continue...

更多

扫码关注架构探险之道,回复『源码』,获取本文相关源码和资源链接

.

知识星球(扫码加入获取历史源码和文章资源链接)

.

这篇关于[Spring] 30个类手写 Spring Mini 版本系列(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/522179

相关文章

Java如何用乘号来重复字符串的功能

《Java如何用乘号来重复字符串的功能》:本文主要介绍Java使用乘号来重复字符串的功能,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java乘号来重复字符串的功能1、利用循环2、使用StringBuilder3、采用 Java 11 引入的String.rep

SpringBoot中HTTP连接池的配置与优化

《SpringBoot中HTTP连接池的配置与优化》这篇文章主要为大家详细介绍了SpringBoot中HTTP连接池的配置与优化的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录一、HTTP连接池的核心价值二、Spring Boot集成方案方案1:Apache HttpCl

Spring Boot项目打包和运行的操作方法

《SpringBoot项目打包和运行的操作方法》SpringBoot应用内嵌了Web服务器,所以基于SpringBoot开发的web应用也可以独立运行,无须部署到其他Web服务器中,下面以打包dem... 目录一、打包为JAR包并运行1.打包为可执行的 JAR 包2.运行 JAR 包二、打包为WAR包并运行

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

Spring Boot 常用注解整理(最全收藏版)

《SpringBoot常用注解整理(最全收藏版)》本文系统整理了常用的Spring/SpringBoot注解,按照功能分类进行介绍,每个注解都会涵盖其含义、提供来源、应用场景以及代码示例,帮助开发... 目录Spring & Spring Boot 常用注解整理一、Spring Boot 核心注解二、Spr

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

详解如何在SpringBoot控制器中处理用户数据

《详解如何在SpringBoot控制器中处理用户数据》在SpringBoot应用开发中,控制器(Controller)扮演着至关重要的角色,它负责接收用户请求、处理数据并返回响应,本文将深入浅出地讲解... 目录一、获取请求参数1.1 获取查询参数1.2 获取路径参数二、处理表单提交2.1 处理表单数据三、

java变量内存中存储的使用方式

《java变量内存中存储的使用方式》:本文主要介绍java变量内存中存储的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍2、变量的定义3、 变量的类型4、 变量的作用域5、 内存中的存储方式总结1、介绍在 Java 中,变量是用于存储程序中数据

如何合理管控Java语言的异常

《如何合理管控Java语言的异常》:本文主要介绍如何合理管控Java语言的异常问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍2、Thorwable类3、Error4、Exception类4.1、检查异常4.2、运行时异常5、处理方式5.1. 捕获异常

Spring Boot集成SLF4j从基础到高级实践(最新推荐)

《SpringBoot集成SLF4j从基础到高级实践(最新推荐)》SLF4j(SimpleLoggingFacadeforJava)是一个日志门面(Facade),不是具体的日志实现,这篇文章主要介... 目录一、日志框架概述与SLF4j简介1.1 为什么需要日志框架1.2 主流日志框架对比1.3 SLF4