[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

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件