手写一个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();
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38520617/article/details/84932493