300行代碼手寫Spring核心--Spring初探

300行代碼手寫Spring核心--Spring初探

目標:我們通過查看源碼的方式一步步嘗試完成springIOC容器的初始化 並完成dispatchServlet的功能

1.首先創建一個我們自己的Servlet並繼承HttpServlet並重寫init方法

public class EVServlet extends HttpServlet {

@Override
    public void init(ServletConfig config) throws ServletException {
        super.init();
    }
}

這一步和我們當初用servlet寫web項目是一樣的調用父類的init方法,我們這裏顯示地調用了父類的init無參方法,其實正常的servlet初始化是容器是調用含參init方法並在方法內部調用this.init(),並且this.config=config的,代碼:

public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }

所以我們正常在重寫父類的init含參方法時需要在一開始顯示地調用父類的有參init方法,這樣給 成員變量config賦了初值,在doget方法等內部隨後纔會獲取,但是在我們這裏只需要加載一次配置文件的類路徑,後續不再需要,就不再顯示地調用了

想一想spring當初完成dispatchServlet都是通過註解完成的,那麼我們就要自己完成當初spring配置好的註解,並在初始化的時候把加了註解的類讀取到內存然後並解析

2.我們創建自己的註解

(1)EVController

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented

public @interface EVController {
}

(2)EVRequestMapping

import java.lang.annotation.*;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVRequestMapping {
    String value() default "";
}

(3)EVAutowired

import java.lang.annotation.*;

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

(4)EVRequestParam

import java.lang.annotation.*;

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

(5)EVService

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

3.我們的容器初始化需要那幾個步驟呢?

@Override
    public void init(ServletConfig config) throws ServletException {
        //1.加載配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.掃描相關的類
        doScanner(contextConfig.getProperty("scanPackage"));

        //3.始化掃描到的類,並且將它們放入到IOC容器之中
        doInstance();

        //4.完成依賴注入
        doAutowired();

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

        System.out.println("EV Spring framework is init.");

        super.init();
    }

分爲五步,先根據我們配置文件定義的類掃描路徑掃描包下帶註解的類,放入IOC容器之中,然後完成依賴注入,並初始化HandlerMapping

4.配置文件

(1)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>Evan Web Application</display-name>
	<servlet>
		<servlet-name>evmvc</servlet-name>
		<servlet-class>v2.servlet.EVServlet</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>evmvc</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>

(2)application.properties(就是初始化讀取的那個配置文件)

因爲只需要個類掃描路徑,就是一句話

scanPackage=demo//我們一會兒在項目路徑下創建個demo包,並把測試類寫在下面

5.骨架搭建好開始填充內容

(0)先創建一些變量


    //保存application.properties配置文件中的內容
    private Properties contextConfig = new Properties();

    //保存掃描的所有的類名
    private List<String> classNames = new ArrayList<String>();

    //傳說中的IOC容器,我們來揭開它的神祕面紗
    //爲了簡化程序,暫時不考慮ConcurrentHashMap
    // 主要還是關注設計思想和原理
    private Map<String,Object> ioc = new HashMap<String,Object>();

    //保存url和Method的對應關係
//    private Map<String,Method> handlerMapping = new HashMap<String,Method>();

    //思考:爲什麼不用Map
    //你用Map的話,key,只能是url
    //Handler 本身的功能就是把url和method對應關係,已經具備了Map的功能
    //根據設計原則:冗餘的感覺了,單一職責,最少知道原則,幫助我們更好的理解
    private List<Handler> handlerMapping = new ArrayList<Handler>();

(1)填充doLoadConfig方法

private void doLoadConfig(String contextConfigLocation) {
        //直接從類路徑下找到Spring主配置文件所在的路徑
        //並且將其讀取出來放到Properties對象中
        //相當於scanPackage=demo 從文件中保存到了內存中
        InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            //存放到Properties變量中
            contextConfig.load(fis);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

ps:關於getResourceAsStream方法的作用請看我轉載的另一篇文章:https://blog.csdn.net/qq_38762479/article/details/89226107,總之是默認從ClassPath根下獲取資源,path不能以’/'開頭,最終是由ClassLoader獲取資源。 

(2)填充doScanner方法

private void doScanner(String scanPackage) {
        //把從配置文件中讀取到的值轉換爲文件路徑,實際上就是把.替換爲/就OK了。
         //我們這裏路徑只有一個demo沒有.,但我們用的是properties文件如果路徑再多一層是有點的
        //classpath
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {
            //如果是文件夾,遞歸
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                  //因爲是類路徑所以都以.class結尾
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String className = (scanPackage + "." + file.getName().replace(".class", ""));
                //存放掃描到的類名
                classNames.add(className);
            }
        }
    }

在url上打一個斷點給大家看一下:

 大概就是這種效果了

(3)填充doInstance方法

private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

                //什麼樣的類才需要初始化呢?
                //加了註解的類,才初始化,怎麼判斷?
                //爲了簡化代碼邏輯,主要體會設計思想,只舉例 @Controller和@Service,
                // @Componment...就不一一舉例了
                if (clazz.isAnnotationPresent(EVController.class)) {
                    Object instance = clazz.newInstance();
                   
                    //Spring默認類名首字母小寫,方法寫在下面
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName, instance);
                } else if (clazz.isAnnotationPresent(EVService.class)) {
                    //1、自定義的beanName
                    EVService service = clazz.getAnnotation(EVService.class);
                    String beanName = service.value();
                    //2、默認類名首字母小寫
                    if ("".equals(beanName.trim())) {
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    //3、根據類型自動賦值,投機取巧的方式
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (ioc.containsKey(i.getName())) {
                            throw new Exception("The “" + i.getName() + "” is exists!!");
                        }
                        //把接口的類型直接當成key了
                        ioc.put(i.getName(), instance);
                    }
                } else {
                    continue;
                }

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


    }
 //如果類名本身是小寫字母,確實會出問題
    //但是我要說明的是:這個方法是我自己用,private的
    //傳值也是自己傳,類也都遵循了駝峯命名法
    //默認傳入的值,存在首字母小寫的情況,也不可能出現非字母的情況

    //爲了簡化程序邏輯,就不做其他判斷了,大家瞭解就OK
    //其實用寫註釋的時間都能夠把邏輯寫完了
    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        //之所以加,是因爲大小寫字母的ASCII碼相差32,
        // 而且大寫字母的ASCII碼要小於小寫字母的ASCII碼
        //在Java中,對char做算學運算,實際上就是對ASCII碼做算學運算
        chars[0] += 32;
        return String.valueOf(chars);
    }

(4)填充Autowired

private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //Declared 所有的,特定的 字段,包括private/protected/default
            //正常來說,普通的OOP編程只能拿到public的屬性
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(EVAutowired.class)) {
                    continue;
                }
                EVAutowired autowired = field.getAnnotation(EVAutowired.class);

                //如果用戶沒有自定義beanName,默認就根據類型注入
                //這個地方省去了對類名首字母小寫的情況的判斷
                //小夥伴們自己去完善
                String beanName = autowired.value().trim();
                if ("".equals(beanName)) {
                    //獲得接口的類型,作爲key待會拿這個key到ioc容器中去取值
                    beanName = field.getType().getName();
                }

                //如果是public以外的修飾符,只要加了@Autowired註解,都要強制賦值
                //反射中叫做暴力訪問, 強吻
                field.setAccessible(true);

                try {
                    //用反射機制,動態給字段賦值
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }


            }

        }
    }

(5)填充initHandlerMapping

private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }

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

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


            //保存寫在類上面的@EVRequestMapping("/demo")
            String baseUrl = "";
            if (clazz.isAnnotationPresent(EVRequestMapping.class)) {
                EVRequestMapping requestMapping = clazz.getAnnotation(EVRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            //默認獲取所有的public方法
            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(EVRequestMapping.class)) {
                    continue;
                }

                //方法上也可能有請求路徑
                EVRequestMapping requestMapping = method.getAnnotation(EVRequestMapping.class);
                //優化
                // //demo///query
                String regex = ("/" + baseUrl + "/" + requestMapping.value())
                        .replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                this.handlerMapping.add(new Handler(pattern, entry.getValue(), method));
//                handlerMapping.put(url,method);
                System.out.println("Mapped :" + pattern + "," + method);

            }


        }

    }

 //保存一個url和一個Method的關係
    public class Handler {
        //必須把url放到HandlerMapping纔好理解吧
        private Pattern pattern;  //正則
        private Method method;
        private Object controller;
        private Class<?>[] paramTypes;

        public Pattern getPattern() {
            return pattern;
        }

        public Method getMethod() {
            return method;
        }

        public Object getController() {
            return controller;
        }

        public Class<?>[] getParamTypes() {
            return paramTypes;
        }

        //形參列表
        //參數的名字作爲key,參數的順序,位置作爲值
        private Map<String, Integer> paramIndexMapping;

        public Handler(Pattern pattern, Object controller, Method method) {
            this.pattern = pattern;
            this.method = method;
            this.controller = controller;

            paramTypes = method.getParameterTypes();

            paramIndexMapping = new HashMap<String, Integer>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {

            //提取方法中加了註解的參數
            //把方法上的註解拿到,得到的是一個二維數組
            //因爲一個參數可以有多個註解,而一個方法又有多個參數
            Annotation[][] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length; i++) {
                for (Annotation a : pa[i]) {
                    if (a instanceof EVRequestParam) {
                        String paramName = ((EVRequestParam) a).value();
                        if (!"".equals(paramName.trim())) {
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }

            //提取方法中的request和response參數
            Class<?>[] paramsTypes = method.getParameterTypes();
            for (int i = 0; i < paramsTypes.length; i++) {
                Class<?> type = paramsTypes[i];
                if (type == HttpServletRequest.class ||
                        type == HttpServletResponse.class) {
                    paramIndexMapping.put(type.getName(), i);
                }
            }

        }


//        private
    }

這就完成容器的初始化

(6)dispatchServlet

然後要考慮如何把請求分發到我們已經儲存的HanderlerMapping

 private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        Handler handler = getHandler(req);
        if (handler == null) {
//        if(!this.handlerMapping.containsKey(url)){
            resp.getWriter().write("404 Not Found!!!");
            return;
        }

        //獲得方法的形參列表
        Class<?>[] paramTypes = handler.getParamTypes();

        Object[] paramValues = new Object[paramTypes.length];

        Map<String, String[]> params = req.getParameterMap();
        for (Map.Entry<String, String[]> parm : params.entrySet()) {
            String value = Arrays.toString(parm.getValue()).replaceAll("\\[|\\]", "")
                    .replaceAll("\\s", ",");

            if (!handler.paramIndexMapping.containsKey(parm.getKey())) {
                continue;
            }

            int index = handler.paramIndexMapping.get(parm.getKey());
            paramValues[index] = convert(paramTypes[index], value);
        }

        if (handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
        }

        if (handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
            int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;
        }

        Object returnValue = handler.method.invoke(handler.controller, paramValues);
        if (returnValue == null || returnValue instanceof Void) {
            return;
        }
        resp.getWriter().write(returnValue.toString());
    }

private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        //絕對路徑
        String url = req.getRequestURI();
        //處理成相對路徑
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");


        for (Handler handler : this.handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

(7)重寫doGet和doPost方法

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

        //6、調用,運行階段
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exection,Detail : " + Arrays.toString(e.getStackTrace()));
        }


    }

(8)寫測試用例

1)接口

public interface IDemoService {
	
	String get(String name);
	
}

 

2)實現Service


/**
 * 核心業務邏輯
 */
@EVService
public class DemoService implements IDemoService {

	public String get(String name) {
		return "My name is " + name;
	}

 

3)Controller

@EVController
@EVRequestMapping("/demo")
public class DemoAction {

  	@EVAutowired
	private IDemoService demoService;

	@EVRequestMapping("/query.*")
	public void query(HttpServletRequest req, HttpServletResponse resp,
					  @EVRequestParam("name") String name){
//		String result = demoService.get(name);
		String result = "My name is " + name;
		try {
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@EVRequestMapping("/add")
	public void add(HttpServletRequest req, HttpServletResponse resp,
					@EVRequestParam("a") Integer a, @EVRequestParam("b") Integer b){
		try {
			resp.getWriter().write(a + "+" + b + "=" + (a + b));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@EVRequestMapping("/sub")
	public void add(HttpServletRequest req, HttpServletResponse resp,
					@EVRequestParam("a") Double a, @EVRequestParam("b") Double b){
		try {
			resp.getWriter().write(a + "-" + b + "=" + (a - b));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@EVRequestMapping("/remove")
	public String  remove(@EVRequestParam("id") Integer id){
		return "" + id;
	}

}

(9)運行結果截圖

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