手寫 Spring

肖朋偉發表於2019-07-20

手寫 Spring

不多說,簡歷裝 X 必備。不過練好還是需要求一定的思維能力。

一、整體思路

思路要熟練背下來

1)配置階段

  • 配置 web.xml: XDispatchServlet
  • 設定 init-param: contextConfigLocation = classpath:application.xml
  • 設定 url-pattern: /*
  • 配置 Annotation: @XController @XService @XAutowired @XRequestMapping

2)初始化階段

  • IOC:
    • 呼叫 init() 方法: 載入配置檔案
    • IOC 容器初始化: Map<String, Object>
    • 掃描相關的類: scan-package="com.xiaopengwei"
    • 建立例項化並儲存到容器: 同過反射機制將類例項化放入 IOC 容器中
  • DI:
    • 進行 DI 操作: 掃描 IOC 容器中的例項,給沒有賦值的屬性自動賦值
  • MVC:
    • 初始化 HandlerMapping: 將一個 URL 和一個 Method 進行一對一的關聯對映 Map<String, Method>

3)執行階段

  • 呼叫 doGet() / doPost() 方法: Web 容器呼叫 doGet() / doPost() 方法,獲得 request/response 物件
  • 匹配 HandleMapping: 從 request 物件中獲得使用者輸入的 url,找到其對應的 Method
  • 反射呼叫 method.invoker(): 利用反射呼叫方法並返回結果
  • response.getWrite().write(): 將返回結果輸出到瀏覽器

二、原始碼

專案結構:

手寫 Spring

原始碼:

(1)在 pom.xml 引入一個 jar 包

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

(2)web.xml 檔案:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>xmvc</servlet-name>
        <servlet-class>com.xiaopengwei.xspring.servlet.XDispatchServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--you can't use classpath*: -->
            <param-value>application.properties</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>xmvc</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

(3)application.properties 檔案:

scan-package=com.xiaopengwei

(4)自定義註解 XAutowired:

package com.xiaopengwei.xspring.annotation;
import java.lang.annotation.*;
/**
 * <p>
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XAutowired {
    String value() default "";
}

(5)自定義註解 XController:

package com.xiaopengwei.xspring.annotation;
import java.lang.annotation.*;
/**
 * <p>
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XController {
    String value() default "";
}

(6)自定義註解 XRequestMapping:

package com.xiaopengwei.xspring.annotation;
import java.lang.annotation.*;
/**
 * <p>
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XRequestMapping {
    String value() default "";
}

(7)自定義註解 XService:

package com.xiaopengwei.xspring.annotation;
import java.lang.annotation.*;
/**
 * <p>
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XService {
    String value() default "";
}

(8)核心 XDispatchServlet:

package com.xiaopengwei.xspring.servlet;
import com.xiaopengwei.xspring.annotation.XAutowired;
import com.xiaopengwei.xspring.annotation.XController;
import com.xiaopengwei.xspring.annotation.XRequestMapping;
import com.xiaopengwei.xspring.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>
 * XSpring
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
public class XDispatchServlet extends HttpServlet {

    /**
     * 屬性配置檔案
     */
    private Properties contextConfig = new Properties();

    private List<String> classNameList = new ArrayList<>();

    /**
     * IOC 容器
     */
    Map<String, Object> iocMap = new HashMap<String, Object>();

    Map<String, Method> handlerMapping = new HashMap<String, Method>();

    @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 {

        //7、執行階段
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception Detail:\n" + Arrays.toString(e.getStackTrace()));
        }

    }

    /**
     * 7、執行階段,進行攔截,匹配
     *
     * @param req  請求
     * @param resp 響應
     */
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {

        String url = req.getRequestURI();

        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        System.out.println("[INFO-7] request url-->" + url);

        if (!this.handlerMapping.containsKey(url)) {
            try {
                resp.getWriter().write("404 NOT FOUND!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = this.handlerMapping.get(url);

        System.out.println("[INFO-7] method-->" + method);


        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        System.out.println("[INFO-7] iocMap.get(beanName)->" + iocMap.get(beanName));

        // 第一個引數是獲取方法,後面是引數,多個引數直接加,按順序對應
        method.invoke(iocMap.get(beanName), req, resp);

        System.out.println("[INFO-7] method.invoke put {" + iocMap.get(beanName) + "}.");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        //1、載入配置檔案
        doLoadConfig(servletConfig.getInitParameter("contextConfigLocation"));

        //2、掃描相關的類
        doScanner(contextConfig.getProperty("scan-package"));

        //3、初始化 IOC 容器,將所有相關的類例項儲存到 IOC 容器中
        doInstance();

        //4、依賴注入
        doAutowired();

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

        System.out.println("XSpring FrameWork is init.");

        //6、列印資料
        doTestPrintData();
    }

    /**
     * 6、列印資料
     */
    private void doTestPrintData() {

        System.out.println("[INFO-6]----data------------------------");

        System.out.println("contextConfig.propertyNames()-->" + contextConfig.propertyNames());

        System.out.println("[classNameList]-->");
        for (String str : classNameList) {
            System.out.println(str);
        }

        System.out.println("[iocMap]-->");
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            System.out.println(entry);
        }

        System.out.println("[handlerMapping]-->");
        for (Map.Entry<String, Method> entry : handlerMapping.entrySet()) {
            System.out.println(entry);
        }

        System.out.println("[INFO-6]----done-----------------------");

        System.out.println("====啟動成功====");
        System.out.println("測試地址:http://localhost:8080/test/query?username=xiaopengwei");
        System.out.println("測試地址:http://localhost:8080/test/listClassName");
    }

    /**
     * 5、初始化 HandlerMapping
     */
    private void initHandlerMapping() {

        if (iocMap.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!clazz.isAnnotationPresent(XController.class)) {
                continue;
            }

            String baseUrl = "";

            if (clazz.isAnnotationPresent(XRequestMapping.class)) {
                XRequestMapping xRequestMapping = clazz.getAnnotation(XRequestMapping.class);
                baseUrl = xRequestMapping.value();
            }

            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(XRequestMapping.class)) {
                    continue;
                }

                XRequestMapping xRequestMapping = method.getAnnotation(XRequestMapping.class);

                String url = ("/" + baseUrl + "/" + xRequestMapping.value()).replaceAll("/+", "/");

                handlerMapping.put(url, method);

                System.out.println("[INFO-5] handlerMapping put {" + url + "} - {" + method + "}.");

            }
        }

    }

    /**
     * 4、依賴注入
     */
    private void doAutowired() {
        if (iocMap.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {

            Field[] fields = entry.getValue().getClass().getDeclaredFields();

            for (Field field : fields) {
                if (!field.isAnnotationPresent(XAutowired.class)) {
                    continue;
                }

                System.out.println("[INFO-4] Existence XAutowired.");

                // 獲取註解對應的類
                XAutowired xAutowired = field.getAnnotation(XAutowired.class);
                String beanName = xAutowired.value().trim();

                // 獲取 XAutowired 註解的值
                if ("".equals(beanName)) {
                    System.out.println("[INFO] xAutowired.value() is null");
                    beanName = field.getType().getName();
                }

                // 只要加了註解,都要載入,不管是 private 還是 protect
                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), iocMap.get(beanName));

                    System.out.println("[INFO-4] field set {" + entry.getValue() + "} - {" + iocMap.get(beanName) + "}.");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 3、初始化 IOC 容器,將所有相關的類例項儲存到 IOC 容器中
     */
    private void doInstance() {
        if (classNameList.isEmpty()) {
            return;
        }

        try {
            for (String className : classNameList) {

                Class<?> clazz = Class.forName(className);

                if (clazz.isAnnotationPresent(XController.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();

                    // 儲存在 ioc 容器
                    iocMap.put(beanName, instance);
                    System.out.println("[INFO-3] {" + beanName + "} has been saved in iocMap.");

                } else if (clazz.isAnnotationPresent(XService.class)) {

                    String beanName = toLowerFirstCase(clazz.getSimpleName());

                    // 如果註解包含自定義名稱
                    XService xService = clazz.getAnnotation(XService.class);
                    if (!"".equals(xService.value())) {
                        beanName = xService.value();
                    }

                    Object instance = clazz.newInstance();
                    iocMap.put(beanName, instance);
                    System.out.println("[INFO-3] {" + beanName + "} has been saved in iocMap.");

                    // 找類的介面
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (iocMap.containsKey(i.getName())) {
                            throw new Exception("The Bean Name Is Exist.");
                        }

                        iocMap.put(i.getName(), instance);
                        System.out.println("[INFO-3] {" + i.getName() + "} has been saved in iocMap.");
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取類的首字母小寫的名稱
     *
     * @param className ClassName
     * @return java.lang.String
     */
    private String toLowerFirstCase(String className) {
        char[] charArray = className.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

    /**
     * 2、掃描相關的類
     *
     * @param scanPackage properties --> scan-package
     */
    private void doScanner(String scanPackage) {

        // package's . ==> /
        URL resourcePath = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));

        if (resourcePath == null) {
            return;
        }

        File classPath = new File(resourcePath.getFile());

        for (File file : classPath.listFiles()) {

            if (file.isDirectory()) {

                System.out.println("[INFO-2] {" + file.getName() + "} is a directory.");

                // 子目錄遞迴
                doScanner(scanPackage + "." + file.getName());

            } else {

                if (!file.getName().endsWith(".class")) {
                    System.out.println("[INFO-2] {" + file.getName() + "} is not a class file.");
                    continue;
                }

                String className = (scanPackage + "." + file.getName()).replace(".class", "");

                // 儲存在內容
                classNameList.add(className);

                System.out.println("[INFO-2] {" + className + "} has been saved in classNameList.");
            }
        }
    }

    /**
     * 1、載入配置檔案
     *
     * @param contextConfigLocation web.xml --> servlet/init-param
     */
    private void doLoadConfig(String contextConfigLocation) {

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            // 儲存在記憶體
            contextConfig.load(inputStream);

            System.out.println("[INFO-1] property file has been saved in contextConfig.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

(9)示例:TestController:

package com.xiaopengwei.demo.xcontroller;
import com.xiaopengwei.demo.xservice.ITestXService;
import com.xiaopengwei.xspring.annotation.XAutowired;
import com.xiaopengwei.xspring.annotation.XController;
import com.xiaopengwei.xspring.annotation.XRequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前置控制器
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@XController
@XRequestMapping("/test")
public class TestController {

    @XAutowired
    ITestXService testXService;

    /**
     * 測試方法 /test/query
     *
     * @param req  請求體
     * @param resp 響應體
     */
    @XRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp) {

        if (req.getParameter("username") == null) {
           try {
                resp.getWriter().write("param username is null");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

            String paramName = req.getParameter("username");
            try {
                resp.getWriter().write("param username is " + paramName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("[INFO-req] New request param username-->" + paramName);
        }
    }

    /**
     * 測試方法 /test/listClassName
     *
     * @param req  請求體
     * @param resp 響應體
     */
    @XRequestMapping("/listClassName")
    public void listClassName(HttpServletRequest req, HttpServletResponse resp) {
        String str = testXService.listClassName();
        System.out.println("testXService----------=-=-=>" + str);
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(10)示例介面:ITestXService:

package com.xiaopengwei.demo.xservice;
/**
 * <p>
 * 介面
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
public interface ITestXService {
    String listClassName();
}

(11)示例實現類 TestXServiceImpl:

package com.xiaopengwei.demo.xservice.impl;
import com.xiaopengwei.demo.xservice.ITestXService;
import com.xiaopengwei.xspring.annotation.XService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 業務實現類
 *
 * @author XiaoPengwei
 * @since 2019-07-19
 */
@XService
public class TestXServiceImpl implements ITestXService {

    @Override
    public String listClassName() {

        // 假裝來自資料庫
        return "123456TestXServiceImpl";
    }
}

(12)測試:

配置 Tomcat 後,訪問:

http://localhost:8080/test/query?username=xiaopengwei

http://localhost:8080/test/listClassName

手寫 Spring

手寫 Spring

相關文章