自己實現spring的基本功能

之前自己做過參數校驗的功能,有使用過註解. 今天就來試試實現spring的類管理

       首先,先理解下spring的思路,spring 將我們需要被管理的類統一的管理起來 然後給需要初始化的類初始化,在遇到web端的請求的時候,根據url來匹配對應的controller的接口方法,進行調用.

       那麼我們要先明白spring 是在什麼時間或者什麼操作節點起作用的,在沒有spring-boot之前我們搭建web項目的時候是怎麼搭建的呢?不知道大家在搭建項目時有沒有注意到webapp文件下的WEN-INF文件夾下有一個web.xml文件.如果沒有注意的同學請去關注下.spring沒有出現之前呢我們搭建web項目跟這個文件打交道的機會還是挺多的.因爲我們的servlet都會在這裏配置.

      然後Spring的做法有一點是一致的,就是我們在使用spring 的時候也需要在web.xml文件配置一個dispatcherServlet. dispatcherServlet繼承了HttpServlet .中所周知HttpServlet 有兩個比較明星的方法 doGet(),doPost(),由於HttpServlet間接的實現了Servlet接口,所以還用另外兩個明星方法init(),destroy().這四個方法起到了關鍵性作用.

我們先了解下servlet生命週期,

    第一階段:

       會調用servlet的init方法,進行一些我們需要爲sevlet的一些行爲/屬性的初始化,官方註釋是說:

        在servlet完成init後代表可以在service發揮作用了

       關於init方法呢,其實servlet中是沒有空參的init()方法的,只有一個init(ServletConfig config)方法.那爲什麼我們的前輩們一般都在init()方法中做初始呢? 原因是GenericServlet這個類是抽象類,他有實現init(ServletConfig config),然後在(ServletConfig config)方法內調用了init()方法.而GenericServlet中的init()是一個空方法(重點:不是抽象方法) . 是不是有點費解? 這個方法的註釋是這樣的這是一個用來簡化在override的時候需要調用super.init(config)的方法.我的理解是,如果我們需要做一些init操作直接覆蓋init()就行了,如果不需要也不用做其他操作.主要是省去了調用super.init(congfig);所以我們在使用servlet需要做初始化的時候,直接override init()方法就行了. 優雅~

    第二階段:

       我們會監聽web發出的請求,通過doGet和doPost還完成.

     第三階段:

       在servlet結束是會調用distroy,可以所以寫“善後” 的事情,官方的註釋說在servlet所提了整個服務時會調用該方法.

瞭解了servlet後,我們應該就清楚了servlet的工作機制.

回過頭來說spring ,spring的四大特點:MVC,IOC,DI,AOP其中:

     IOC:控制反轉,就是bean的創建交給Spring來管理,那現在我要模仿一個spring也就是說bean 的創建應該由我來管理,所以我應該在程序的一開始就做這部分工作. 從上邊的servlet的工作機制我就明白我要在servlet的init()其中一部分就是模仿ioc的bean管理.

     DI:ioc我模仿了那肯定也得完成依賴注入的工作,現在有確定了一部分.

     MVC:我們知道當spring 接收到請求後會根據url進行匹配對應的controller 的對應接口.所以這個匹配關係也應該放在init()方法中

     AOP:我們都是到aop其實就是代理,不論是哪種代理我們都是動態生成一個新的類來完成功能.所以這部分也要在init中完成.

現在spring的特性都明確了需要在哪實現.接下來就是去做了.

那在實現的時候我們大致分三個階段:

   1.在數據初始化的時候spring會將我們在配置文件中的配置加載並封裝

   2.將所有的類初始化一邊並且將實例保存在IOC容器中,我們有了所有的容器就可以完成spring的AOP和DI(依賴注入).

   3.將所有的controller 的path保存起來(也就是我們常說的handlerMapping)

以上的完成後就可以等待web訪問了.

廢話不多說上代碼首先是註解(由於註解都是模仿spring的格式來的所以我們可以根據註解名字對錶spring,功能一致):

package com.shuguolili.mvcframework.annotation;

import java.lang.annotation.*;



@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SGAutowired {
    String value() default "";
}

下面幾個註解我就不再上代碼了,如果卻是又朋友需要評論說下我再上,不然篇幅太長.

           

接着就是我們的核心DispatchDispatchServlet

package com.shuguolili.mvcframework.servlet;


import com.shuguolili.mvcframework.annotation.SGAutowired;
import com.shuguolili.mvcframework.annotation.SGController;
import com.shuguolili.mvcframework.annotation.SGRequestMapping;
import com.shuguolili.mvcframework.annotation.SGService;

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.Method;
import java.net.URL;
import java.util.*;

/**
 * @program springdemo
 * @description: 自己實現的類似springDispatchServlet的類
 * @author: yang
 * @create: 2020/03/31 15:00
 */

public class SGDispatchServlet extends HttpServlet {

    //創建一個map用來存放url和接口的映射關係,spring 實際是將url和對應的handler封裝在HandlerMapping中然後在通過list存放
    private Map<String,Object> mapping = new HashMap<String, Object>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.getStackTrace();
            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();
        Object o = this.mapping.get(method.getDeclaringClass().getName());
        method.invoke(o,new Object[]{req,resp,params.get("name")[0]});
    }

    @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);
            Set<String> strings = mapping.keySet();
            List<String> names = new ArrayList<String>();
            for(String className : strings){
                names.add(className);
            }
            for (String className : names) {
                if(!className.contains(".")){continue;}
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(SGController.class)){
                    mapping.put(className,clazz.newInstance());
                    String baseUrl = "";
                    if (clazz.isAnnotationPresent(SGRequestMapping.class)) {
                        SGRequestMapping requestMapping = clazz.getAnnotation(SGRequestMapping.class);
                        baseUrl = requestMapping.value();
                    }
                    Method[] methods = clazz.getMethods();
                    for (Method method : methods) {
                        if (!method.isAnnotationPresent(SGRequestMapping.class)) {  continue; }
                        SGRequestMapping requestMapping = method.getAnnotation(SGRequestMapping.class);
                        String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                        mapping.put(url, method);
                        System.out.println("Mapped " + url + "," + method);
                    }
                }else if(clazz.isAnnotationPresent(SGService.class)){
                    SGService service = clazz.getAnnotation(SGService.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(SGController.class)){
                    Field[] fields = clazz.getDeclaredFields();
                    for (Field field : fields) {
                        if(!field.isAnnotationPresent(SGAutowired.class)){continue; }
                        SGAutowired autowired = field.getAnnotation(SGAutowired.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) {
            System.out.println("error : "+ Arrays.toString(e.getStackTrace()));
        }finally {
            if(is != null){
                try {is.close();} catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.print("SG MVC Framework is init success");
    }
    
    /**
     * @description:  掃描指定的包路徑
     * @param: scanPackage 
     * @return: void
     * @author: yang
     * @date: 
     */
    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);
            }
        }
    }
}

其中的init的方法作用就是將需要交給spring管理的類在mapping中進行初始化並完成依賴注入. 其中將handletMaaping和path的映射

也存放在mapping中這樣當我們自己實現的dispatchserlvet在接收到請求的時候就可以通過mapping判斷請求及對應的controller 的對應接口,完成web訪問.

爲了檢驗是否功能正常,添加一個servlce和action來試試

srvice接口:

package com.shuguolili.demo.service;

/**
 * @program springdemo
 * @description: service層
 * @author: yang
 * @create: 2020/03/31 15:15
 */

public interface IDemoService {

    String get(String name);

}

service

package com.shuguolili.demo.service.impl;

import com.shuguolili.demo.service.IDemoService;
import com.shuguolili.mvcframework.annotation.SGService;

/**
 * @program springdemo
 * @description: service 層
 * @author: yang
 * @create: 2020/03/31 15:16
 */
@SGService
public class DemoService implements IDemoService {

    public String get(String name) {
        return "resquest name is " + name + ",this words from service.";
    }
}

controller:只有一個接口,調用來service的get方法

package com.shuguolili.demo.mvc.action;

import com.shuguolili.demo.service.IDemoService;
import com.shuguolili.mvcframework.annotation.SGAutowired;
import com.shuguolili.mvcframework.annotation.SGController;
import com.shuguolili.mvcframework.annotation.SGRequestMapping;
import com.shuguolili.mvcframework.annotation.SGRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program springdemo
 * @description: controller層
 * @author: yang
 * @create: 2020/03/31 15:17
 */
//雖然,用法一樣,但是沒有功能
@SGController
@SGRequestMapping("/demo")
public class DemoAction {

    @SGAutowired
    private IDemoService demoService;

    @SGRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp,
                      @SGRequestParam("name") String name){
        String result = demoService.get(name);
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  

}

結果展示:

OK,到目前爲止成功了最最簡單的spring 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章