手写迷你Spring框架
Posted 向着百万年薪努力的小赵
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写迷你Spring框架相关的知识,希望对你有一定的参考价值。
随着不断地使用Spring,以及后续的Boot、cloud,不断的体会到这个拯救Java的生态体系的强大,也使我对于这个框架有了极大的好奇心,以至于产生了我为什么不能写一个这样的框架的思考。
通过自学及参考谭勇德(Tom)老师的《Spring 5核心原理》这本书,决定记录我手写Spring的过程,记录此系列博客 。
愿每个想探究Spring原理的人,学习道路一帆风顺
文章目录
Spring最初的时候,其功能远远不如现在强大,甚至我在看Spring最初版本的时候有种这就是所谓的Spring?的疑问,但随后便恍然大悟,我是站立在历史的下游,用后人的眼光去看前人的作品,当然有种站在制高点俯视的感觉,当我一步一步深入学习Spring的设计思想设计理念以及实现方式的时候,无不为前人那惊天地泣鬼神的思想所震撼。
话不多说进入主题:
正常的创建一个web项目就好
1 准备阶段——自定义配置
1.1 配置application.properties
为了解析方便,我们用application.properties来作为配置文件,内容很简单,如下:
scanPackage=com.gupaoedu.demo
1.2 配置web.xml文件
大家都知道,所有依赖于Web容器的项目都是从读取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>XiaoZhao Web Application</display-name>
<servlet>
<servlet-name>zhao mvc</servlet-name>
<servlet-class>com.xiaoZhao666.mvcframework.v1.servlet.DispatchServlet</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>zhao mvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
其中DispatchServlet
是模拟Spring实现的核心功能类
1.3 自定义注解
做就做全套,我们连注解也给他模拟了,在自己包下创建annotation包,下面用的注解都是咱们自己创建的
1.3.1 @Service
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Service
String value() default "";
1.3.2 @Autowired
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired
String value() default "";
1.3.3 @Controller
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Controller
String value() default "";
1.3.4 @RequestMapping
@Target(ElementType.TYPE,ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestMapping
String value() default "";
1.3.5 @RequestParam
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam
String value() default "";
1.4 配置注解
配置业务实现类,此时文件结构如下
接口:
public interface IDemoService
String get(String name);
实现类:
/**
* 核心业务逻辑
*/
@Service
public class DemoService implements IDemoService
@Override
public String get(String name)
return "My name is " + name + ",from service.";
配置请求入口DemoAction:
@Controller
@RequestMapping("/demo")
public class DemoAction
@Autowired
private IDemoService demoService;
@RequestMapping("/query")
public void query(HttpServletRequest req, HttpServletResponse resp,
@RequestParam("name") String name)
String result = demoService.get(name);
try
resp.getWriter().write(result);
catch (IOException e)
e.printStackTrace();
@RequestMapping("/add")
public void add(HttpServletRequest req, HttpServletResponse resp,
@RequestParam("a") Integer a, @RequestParam("b") Integer b)
try
resp.getWriter().write(a + "+" + b + "=" + (a + b));
catch (IOException e)
e.printStackTrace();
@RequestMapping("/remove")
public String remove(@RequestParam("id") Integer id)
return "" + id;
至此,我们的所有配置就算完成了。
2 容器初始化
2.1 实现Spring 1.0版本
1.0版本只是有了一些简单的逻辑,对于以前写Servlet的老同学来说,看着会无比亲切,这一块没啥好说的,Spring的底层就是Servlet嘛。
核心逻辑都在init
方法里了,让我们迅速过度到下一阶段2.0版本
public class DispatcherServlet extends HttpServlet
private Map<String,Object> mapping = new HashMap<String, Object>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException this.doPost(req,resp);
@Override
protected 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()));
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception
String url = req.getRequestURI();
String contextPath = req.getContextPath();
url = url.replace(contextPath, "").replaceAll("/+", "/");
if(!this.mapping.containsKey(url))resp.getWriter().write("404 Not Found!!");return;
Method method = (Method) this.mapping.get(url);
Map<String,String[]> params = req.getParameterMap();
method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]req,resp,params.get("name")[0]);
//当我晕车的时候,我就不去看源码了
//init方法肯定干得的初始化的工作
//inti首先我得初始化所有的相关的类,IOC容器、servletBean
@Override
public void init(ServletConfig config) throws ServletException
InputStream is = null;
try
Properties configContext = new Properties();
is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));
configContext.load(is);
String scanPackage = configContext.getProperty("scanPackage");
doScanner(scanPackage);
for (String className : mapping.keySet())
if(!className.contains("."))continue;
Class<?> clazz = Class.forName(className);
if(clazz.isAnnotationPresent(Controller.class))
mapping.put(className,clazz.newInstance());
String baseUrl = "";
if (clazz.isAnnotationPresent(RequestMapping.class))
RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
baseUrl = requestMapping.value();
Method[] methods = clazz.getMethods();
for (Method method : methods)
if (!method.isAnnotationPresent(RequestMapping.class)) continue;
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
mapping.put(url, method);
System.out.println("Mapped " + url + "," + method);
else if(clazz.isAnnotationPresent(Service.class))
Service service = clazz.getAnnotation(Service.class);
String beanName = service.value();
if("".equals(beanName))beanName = clazz.getName();
Object instance = clazz.newInstance();
mapping.put(beanName,instance);
for (Class<?> i : clazz.getInterfaces())
mapping.put(i.getName(),instance);
else continue;
for (Object object : mapping.values())
if(object == null)continue;
Class clazz = object.getClass();
if(clazz.isAnnotationPresent(Controller.class))
Field [] fields = clazz.getDeclaredFields();
for (Field field : fields)
if(!field.isAnnotationPresent(Autowired.class))continue;
Autowired autowired = field.getAnnotation(Autowired.class);
String beanName = autowired.value();
if("".equals(beanName))beanName = field.getType().getName();
field.setAccessible(true);
try
field.set(mapping.get(clazz.getName()),mapping.get(beanName));
catch (IllegalAccessException e)
e.printStackTrace();
catch (Exception e)
finally
if(is != null)
try is.close(); catch (IOException e)
e.printStackTrace();
System.out.print("MVC Framework is init");
private void doScanner(String scanPackage)
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;
String clazzName = (scanPackage + "." + file.getName().replace(".class",""));
mapping.put(clazzName,null);
2.2 实现Spring 2.0版本
让我们迅速过度到2.0版本,改造1.0版本的DispatchServlet。
我们在1.0的版本上进行优化,加入Spring中使用的设计模式(工厂模式,单例模式,委派模式,策略模式),将init()方法中的代码进行封装。按照Spring框架的实现思路,先搭基础框架,再“填肉注血”,具体代码如下:
2.2.1 将init()方法中的代码进行改造
@Override
public void init(ServletConfig config) throws ServletException
//1、加载配置文件
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//2、扫描相关的类
doScanner手写迷你 SpringMVC 框架