手寫一個Spring框架(不含AOP)

spring 手寫分三個階段:

1.配置階段:

web.xml配置

servlet初始化

2.初始化階段:

加載配置文件

ioc容器初始化

掃描相關的類

類實例化,並注入ioc容器

將url路徑和相關method進行映射關聯

3運行階段

dopost作爲入口

根據url找到method,通過反射去運行method;

response.getWriter(().wirte();

 

項目結構圖如下:

一.配置階段:

項目本身是maven項目,pom文件只配了servlet-api和jetty

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>com.wj.Spring</groupId>
    <artifactId>Spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.5.v20170502</version>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <httpConnector>
                    <port>8080</port>
                </httpConnector>
                <webApp>
                    <contextPath>/</contextPath>
                </webApp>
            </configuration>
        </plugin>
        </plugins>
    </build>
</project>

然後創建DispatcherServlet 使其繼承HttpServlet,重寫dopost,doGet 以及 init 方法


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

      
    }

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

    }

配置web.xml  如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


    <servlet>
        <servlet-name>demoMvc</servlet-name>
        <servlet-class>com.wj.spring.mvcframework.servlet.DispatcherServlet</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>demoMvc</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


</web-app>

配置spring 核心配置文件application的路徑

application.properties的內容只有一個掃描路徑:

接下來配置註解:springMvc常用註解:

@Controller  @Service @RequestMapping  @Autowired  @RequestParam

這些我們都將重寫,替換成自己的註解

1)@DemoController

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */

//類上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoController {

    String value() default "";
}

2)@DemoService

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */

//類上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoService {

    String value() default "";
}

3) @DemoRequestMapping

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestMapping {
    String value() default "";
}

4)@Autowired

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoAutowired {
    String value() default "";
}

5) @DemoRequestParam    該註解因爲在配置時把參數名字寫死了,所以下文沒用上

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestParam {
    String value() default "";
}

創建測試類:DemoAction  ;  DemoServiceImpl implements MyService

1)DemoAction:

package com.wj.spring.demo.action;

import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 小美女 on 2018/12/9.
 */
@DemoController
@DemoRequestMapping("/demo")
public class DemoAction {

    @DemoAutowired
    private MyService myService;
    @DemoRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp,@DemoRequestParam("name") String name){
        String result =myService.get(name);
        try {

            //寫入頁面
            resp.getWriter().write(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @DemoRequestMapping("/add")
    public void add(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("a") Integer a,@DemoRequestParam("b") Integer b){
        try {

            resp.getWriter().write(a+"+"+b+"="+(a+b));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @DemoRequestMapping("/remove")
    public void remove(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("id") Integer id){

    }

}

2)MyService:

package com.wj.spring.demo.service;


/**
 * Created by 小美女 on 2018/12/9.
 */
public interface MyService {
    public String get(String name);
}

3) DemoServiceImpl implements MyService:

package com.wj.spring.demo.service.impl;

import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoService;

/**
 * Created by 小美女 on 2018/12/9.
 */
@DemoService
public class DemoServiceImpl implements MyService {
    public String get(String name) {
        return "my name is :"+name;
    }
}

2.初始化階段:

在DispatcherServlet中添加成員變量;

 

當web項目啓動時,會啓動Servlet容器並加載DispatcherServlet 的init()方法,從init()方法的參數中,我們可以拿到application.properties文件的路徑,並讀取其中的屬性(掃描路徑);在init()方法中添加初始化內容:

 @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("my Spring init");
    }

1)doLoadConfig()方法,將配置文件讀取到Pripeties 中

private void doLoadConfig(String contextConfigLocation) {
        //反射加載過程有講到過讀取classPath下的配置文件方法
        InputStream is =  this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2)doScanner(),遞歸掃描所有的Class文件

   private void doScanner(String scanPackage) {
        //得到一個url(將所有的“.“替換成”/“)
        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")){ //如果不是文件夾,是文件
                  String className =     (scanPackage+"."+file.getName()).replace(".class","");
                  //獲取到所有class文件的路徑,存入一個list中
                  classNames.add(className);
                }
            }

        }

    }

3)doInstance()方法,初始化相關的類,並將其放入Ioc容器中(一個map)ioc的key默認是類名首字母小寫,爲此還寫了個lowerFirstCase(String beanName) 方法:

 private void doInstance() {
        //將掃描到的類進行反射
        try {
            if(classNames.isEmpty()){
                return;
            }

            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                //將實例化後的對象保存進IOC容器;

                if(clazz.isAnnotationPresent(DemoController.class)){
                    Object o = clazz.newInstance();
                    //類名首字母小寫,建立一個lowerFirstCase方法(轉換成char[] 數組操作  chars[0]+=32)
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,o);
                }else if(clazz.isAnnotationPresent(DemoService.class)){
                    // service 注入的不是他本身,而是它的實現類
                    //1.默認類名首字母小寫(Interface)

                    //2.自定義beanName;
                    DemoService demoService = clazz.getAnnotation(DemoService.class);
                    String beanName = demoService.value();
                    if("".equals(beanName)){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object o = clazz.newInstance();
                    ioc.put(beanName,o);
                    //3. 如果是接口的實現(impl)的話,用他的接口類型作爲key
                    Class<?>[] interfaces =  clazz.getInterfaces();
                    for(Class<?> i :interfaces){
                        //如果一個接口有多個實現類,會出現重複的情況
                        if(ioc.containsKey(i.getName())){
                            throw  new Exception("The beanName is exists");
                        }
                        ioc.put(i.getName(),o);
                    }
                }else{
                    continue;
                }

            }

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

    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return  String.valueOf(chars);
    }

 

4)doAutowired()方法,爲Ioc容器中類的屬性賦值

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

        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //獲取所有屬性(包括私有)
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field :fields){
                //只注入Autowired註解
                if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}

                DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
                String beanName = demoAutowired.value().trim();
                if("".equals(beanName)){//如果註解裏的屬性名是空的話,使用類名

                    beanName = field.getType().getName();
                }


                field.setAccessible(true);
                try {
                    //使用反射爲屬性賦值
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

5)initHandlerMapping()方法,將訪問時的url和DemoAction 的方法關聯

private void initHandlerMapping() {
        //找到方法路徑
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(DemoController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
                DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
                baseUrl = demoRequestMapping.value();
            }


            //這裏不需要獲取private的方法,Spring源碼中也是這樣的
            Method[] methods = clazz.getMethods();

            for(Method method:methods){
                //只用requestMapping 的方法才需要映射
                if(!method.isAnnotationPresent(DemoRequestMapping.class)){
                    continue;
                }

                DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
                //多個“/” 替換成一個“/”;
                String url  = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");

                handlerMapping.put(url,method);
                System.out.println("Mapped:"+url+","+method);
            }

        }


    }

3.運行階段

運行時,用戶發送的請求都會被DispatcherServlet 接受,統一調用dopost方法,因此在dopost()方法中添加doDispatch()方法

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

        //運行階段,根據用戶請求的url,進行調動
        try {
            doDispatch(req,resp);
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        if(this.handlerMapping.isEmpty()){return;}
        //絕對路徑
        String url =  req.getRequestURI();

        //絕對路徑處理成相對路徑
        String contextPath = req.getContextPath();
        url =  url.replace(contextPath,"").replaceAll("/+","/");

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

        Method method =this.handlerMapping.get(url);
        //反射調用
        //1.方法所在類的實例(從IOC容器中拿)
        //這裏沒有辦法獲得IOCmap中的key,只能通過方法所在類的類名首字母小寫獲得,與Spring的方法不同
        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());

        //瀏覽器參數
        Map<String,String[]>params = new HashMap<String, String[]>();
        params = req.getParameterMap();
        method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});

    }

到此整個配置完成;在瀏覽器輸入地址:

 

以下是DispatcherServlet的全部代碼:

package com.wj.spring.mvcframework.servlet;

import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
public class DispatcherServlet extends HttpServlet{


    private Properties contextConfig = new Properties();

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


    //ioc容器
    Map<String,Object> ioc = 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 {

        //運行階段,根據用戶請求的url,進行調動
        try {
            doDispatch(req,resp);
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        if(this.handlerMapping.isEmpty()){return;}
        //絕對路徑
        String url =  req.getRequestURI();

        //絕對路徑處理成相對路徑
        String contextPath = req.getContextPath();
        url =  url.replace(contextPath,"").replaceAll("/+","/");

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

        Method method =this.handlerMapping.get(url);
        //反射調用
        //1.方法所在類的實例(從IOC容器中拿)
        //這裏沒有辦法獲得IOCmap中的key,只能通過方法所在類的類名首字母小寫獲得,與Spring的方法不同
        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());

        //瀏覽器參數
        Map<String,String[]>params = new HashMap<String, String[]>();
        params = req.getParameterMap();
        method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});

    }

    @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("my Spring init");
    }

    private void initHandlerMapping() {
        //找到方法路徑
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(DemoController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
                DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
                baseUrl = demoRequestMapping.value();
            }


            //這裏不需要獲取private的方法,Spring源碼中也是這樣的
            Method[] methods = clazz.getMethods();

            for(Method method:methods){
                //只用requestMapping 的方法才需要映射
                if(!method.isAnnotationPresent(DemoRequestMapping.class)){
                    continue;
                }

                DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
                //多個“/” 替換成一個“/”;
                String url  = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");

                handlerMapping.put(url,method);
                System.out.println("Mapped:"+url+","+method);
            }

        }


    }

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

        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //獲取所有屬性(包括私有)
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field :fields){
                //只注入Autowired註解
                if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}

                DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
                String beanName = demoAutowired.value().trim();
                if("".equals(beanName)){//如果註解裏的屬性名是空的話,使用類名

                    beanName = field.getType().getName();
                }


                field.setAccessible(true);
                try {
                    //使用反射爲屬性賦值
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void doInstance() {
        //將掃描到的類進行反射
        try {
            if(classNames.isEmpty()){
                return;
            }

            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                //將實例化後的對象保存進IOC容器;

                if(clazz.isAnnotationPresent(DemoController.class)){
                    Object o = clazz.newInstance();
                    //類名首字母小寫,建立一個lowerFirstCase方法(轉換成char[] 數組操作  chars[0]+=32)
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,o);
                }else if(clazz.isAnnotationPresent(DemoService.class)){
                    // service 注入的不是他本身,而是它的實現類
                    //1.默認類名首字母小寫(Interface)

                    //2.自定義beanName;
                    DemoService demoService = clazz.getAnnotation(DemoService.class);
                    String beanName = demoService.value();
                    if("".equals(beanName)){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object o = clazz.newInstance();
                    ioc.put(beanName,o);
                    //3. 如果是接口的實現(impl)的話,用他的接口類型作爲key
                    Class<?>[] interfaces =  clazz.getInterfaces();
                    for(Class<?> i :interfaces){
                        //如果一個接口有多個實現類,會出現重複的情況
                        if(ioc.containsKey(i.getName())){
                            throw  new Exception("The beanName is exists");
                        }
                        ioc.put(i.getName(),o);
                    }
                }else{
                    continue;
                }

            }

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

    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return  String.valueOf(chars);
    }

    private void doScanner(String scanPackage) {
        //得到一個url(將所有的“.“替換成”/“)
        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")){ //如果不是文件夾,是文件
                  String className =     (scanPackage+"."+file.getName()).replace(".class","");
                  //獲取到所有class文件的路徑,存入一個list中
                  classNames.add(className);
                }
            }

        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        //反射加載過程有講到過讀取classPath下的配置文件方法
        InputStream is =  this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

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