• 仿SpringBoot启动Dome实现


    前言

    填一下以前这篇博文:如何纯注解整合Spring SpringMVC Mybatis埋下的坑,我们来简单的了解一下SpringBoot它做的一些自动配置是怎么一回事,同时也看看SpringBoot如何做到内置服务器的(其实这两货是一样的)

    那么在开始之前呢,我们先简单回顾一下,Spring,SpringMVC,SpringBoot的一个关系。首先我们来聊一下这个Spring,这个家伙呢,在为我们开发项目的时候呢,提供了很多有利于项目开发的解决方案,其中比较出名的是它提供的IOC,和 AOP这两个家伙便于我们对项目的对象进行管理和功能的实现。MVC呢是为了解决Servlet这个玩意不好用,同时为了高效开发,在Dispatch这个地方做了点手脚,让请求经过MVC,之后由我们按照MVC要求的风格编写出来的代码执行对应的逻辑。也就是说,Tomcat提供Servlet操作服务器,MVC在Servlet的基础上做代码优化省略不必要的额外开发,说白了做了一个工具包。但是这个工具包基于Spring来实现,同时可以共享IOC容器,也就是说可以通过Spring结合其他的组件,例如SpringData,或者国内比较常用的Mybatis,完成最基础的CURD的项目的开发,但是由于为了能够让Spring去不断整合更多的玩意,实现更加复杂的功能,于是SpringBoot做了一件事情就是约定大于配置,于是把很多东西直接整合好了。也就是做了一个类似于脚手架的东西,开发者不需要从0开始配置组合、换一句话说,根据任务需求,有一个配置好了大部分组件的Spring。于是你拿过来改一下就差不多了。并且SpringBoot提供了一种约束大家按照这格约束来,就可以更快的组合项目。比如我们的starter,starter就像一个组件,SpringBoot是一个架子,把Starter放进来,就完成了大部分的组装工作。此外,对于SpringBoot而言它还直接把服务器默认给配置好了,项目启动时只需要配置端口即可。

    那么我们这边要做的就是看看这个玩意那些自动配置咋做的,如何把服务器给内置进去的。

    环境搭建

    首先我们来看到一个SpringBoot启动类,我们来看到有什么东西。

    在这里插入图片描述

    这里有一个注解,然后有一个run方法,方法传递类对象,以及参数,参数也可以不传递。

    之后项目启动的时候,服务器就启动了。那么我们这边也是创建一个dome,我们来简单仿造一下怎么做的。

    这边创建了这样的项目:
    在这里插入图片描述

    这里的话是创建了一个root工程的,没啥作用,就是用来聚合这两个项目的。上面那个就是我们要仿造的dome,下面是我们模仿使用。

    依赖

    依赖的话分别如下:
    由于SpringBoot是自己内置了几个服务器的,因此我们这边也是做一个模拟,也要导入多格服务器,比如Tomcat和Jetty,但是呢,默认的是Tomcat,所以的话,我们这边对Jetty服务器要做一个避免依赖传递。

    
    <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.0modelVersion>
    
        <groupId>com.huteroxgroupId>
        <artifactId>springbootartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.18version>
            dependency>
    
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webartifactId>
                <version>5.3.18version>
            dependency>
    
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-aopartifactId>
                <version>5.3.18version>
            dependency>
    
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>5.3.18version>
            dependency>
    
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>javax.servlet-apiartifactId>
                <version>4.0.1version>
            dependency>
    
            <dependency>
                <groupId>org.apache.tomcat.embedgroupId>
                <artifactId>tomcat-embed-coreartifactId>
                <version>9.0.60version>
            dependency>
    
    
            <dependency>
                <groupId>org.eclipse.jettygroupId>
                <artifactId>jetty-serverartifactId>
                <version>9.4.48.v20220622version>
                <optional>trueoptional>
            dependency>
    
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    那么使用的那个就简单了:

    
    <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.0modelVersion>
    
        <groupId>com.huteroxgroupId>
        <artifactId>usebootartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>com.huteroxgroupId>
                <artifactId>springbootartifactId>
                <version>1.0-SNAPSHOTversion>
            dependency>
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    直接使用就好了。

    项目结构

    依赖导入完了,但是还不够,因为的话,在用SpringBoot的时候,我们以前只需要导入SpringBoot和web-starter的依赖就可以处理请求了,那么我们也要实现这个。而且这边都要做内置服务器,因此也需要做出来。

    首先看到我们的使用,非常简单。项目结构如下:
    在这里插入图片描述

    package com.huterox;
    
    
    import com.huterox.annoation.HSpringBootApplication;
    import com.huterox.boot.HSpringApplication;
    
    @HSpringBootApplication
    public class UseBootApplication {
    
        public static void main(String[] args) {
            HSpringApplication.run(UseBootApplication.class);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    package com.huterox.controller;
    
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class UserBootController {
    
        @GetMapping("/hello")
        public String hello(){
            return "hello world";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    之后的话是我们仿造的dome的结构。
    在这里插入图片描述
    在这里插入图片描述

    实现

    OK,这个就是咱们最基本的实现。
    首先自然就是这个启动类,以及对应的启动的注解了。

    启动

    我们先来看到我们的类实现。

    
    public class HSpringApplication {
        /**
         * 启动Tomcat 以及对应上下文 给mvc
         * */
        public static void run(Class  clazz){
            AnnotationConfigWebApplicationContext applicationContext = new
                    AnnotationConfigWebApplicationContext();
    
            applicationContext.register(clazz);
            applicationContext.refresh();
    
            WebServer webServer = getWebServer(applicationContext);
            webServer.start();
    
        }
    	
    	//获取服务器,把服务器实例化在容器里面,然后拿出来启动,但是默认支持一个
        private static WebServer getWebServer(WebApplicationContext applicationContext) {
    
            Map<String, WebServer> beansOfType = applicationContext.getBeansOfType(WebServer.class);
            if(beansOfType.size()==0){
                throw new NullPointerException("未找到对应服务器依赖");
            }else if(beansOfType.size()>1){
                throw new RuntimeException("期望存在一个服务器依赖,但是发现多个请指定具体某一个");
            }
            return beansOfType.values().stream().findFirst().get();
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    这里的话我们简单一点,只需要传递类就好了。

    之后是注解:

    package com.huterox.annoation;
    
    
    import com.huterox.autoConfig.webServer.auto.WebServerAutoConfig;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Import;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @ComponentScan
    @Import({WebServerAutoConfig.class})
    public @interface HSpringBootApplication {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    我们这块使用到了一个注解@ComponentScan 是我们Spring里面的,那么当我们加载到使用了这个注解的类的时候,Spring会解析上面的注解,发现有@ComponentScan于是就会默认扫描那个所在类下面的所有的包,然后把类放在IOC里面。所以这个也是为什么我们创建SpringBoot项目的时候那个启动类一般是在最外面的。

    获取服务器

    之后的话我们还要获取服务器,这里我们定义了这个
    在这里插入图片描述

    一个接口,两个实现类。我们先来看到接口,这里的话我们先简单模拟一下。

    public interface WebServer {
    
        void start();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    public class JettyServer implements WebServer {
        @Override
        public void start() {
            System.out.println("我是Jetty Jerry的弟弟 Tom抓不到我嘿嘿~");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    public class TomCatServer implements WebServer {
        @Override
        public void start() {
            System.out.println("我是Tom 我来抓 Jerry的弟弟Jetty");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    这个实现类的话,我们先这样简单模拟一下,待会我们再来实现具体的功能,这个玩意干嘛的呢,就是用来启动我们服务器的。我们一般启动服务器是例如Tomcat,是配置了XML文件,比如什么路径呀之类的,然后呢去启动。那么我们这边也是只是我们这边先帮你做好基本配置,然后直接帮你启动好,这个配置包括对Tomcat整合MVC的配置。

    自动配置

    那么这样做还不够,我们还需要写一个配置类。我们刚刚启动类里面是需要获取到我们的服务器实例,并且我们需要放在IOC里面,那么这个时候我们就需要配置类来实现。

    
    @Configuration
    public class WebServerAutoConfig {
    
        @Bean
        @HCondationOnClass("org.apache.catalina.startup.Tomcat")
        public TomCatServer tomCatServer(){
            return new TomCatServer();
        }
    
        @Bean
        @HCondationOnClass("org.eclipse.jetty.server.Server")
        public JettyServer jettyServer(){
            return new JettyServer();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    也就是说,和以前不一样的是,以前配置类现在用户自己的项目里面,现在的话我们写在了SpringBoot里面,同时我们还需要加载到这个配置,于是我们还需要在配置当中引入于是我们在启动的时候引入了这个玩意。
    在这里插入图片描述

    不过值得一提的是,在真正的SpringBoot里面实现是通过这个注解来实现的。
    在这里插入图片描述

    它里面是这个:
    在这里插入图片描述
    他也有一个导入,但是导入的自动导入配置的一个选择器。这个玩意是啥呢,这个呢就是负责加载全部的一个自动配置类的东西,因为在SpringBoot里面不可能只有一个东西需要配置,于是有了这个玩意。同时有一个规范,那就是第三方的东西要整合的时候,比如MP,在MP里面可以写好那个自动配置类,然后呢SpringBoot把这个拿到容器里面。没错自动配置类要么是SpringBoot开发人员写好了,要么是第三方平台写好了,当然用户也可以自动定义配置类。那么第三方平台只需要告诉SpringBoot那个自动类在哪就好了。比如Mp的
    在这里插入图片描述
    这样就好了。但是咱们这块就算了简化一下。

    这个时候呢,我们的自动配置类里面有两个服务器,显然是不合适的。需要选择配置。
    包括我们的SpringBoot本身也是这样的,如果我们需要使用Jetty的时候呢。我们是排除了Tomcat的依赖然后导入了Jetty的依赖的。
    所以的话在实现的时候要做一个条件注入。

    @Target({ElementType.TYPE,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Conditional(HCondationClass.class)
    public @interface HCondationOnClass {
        String value();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    之后这样处理

    
    public class HCondationClass implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    
            Map<String, Object> allAnnotationAttributes = metadata.getAnnotationAttributes(HCondationOnClass.class.getName());
            assert allAnnotationAttributes != null;
            String value = (String) allAnnotationAttributes.get("value");
            try {
                Class<?> aClass = Objects.requireNonNull(context.getClassLoader()).loadClass(value);
                return true;
            } catch (ClassNotFoundException e) {
                return false;
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    这个条件注入也是依赖的Spring的条件注入。

    到此我们简要测试一下:
    在这里插入图片描述

    这个时候的话我们就启动了我们模拟的服务器。

    启动Tomcat

    但是这个还不够,我们得真的实现一下,这个我们这里只实现一下Tomcat,我们把代码改一下。
    接口也换一下:

    
    public class TomCatServer implements WebServer {
        @Override
        public void start(WebApplicationContext applicationContext) {
            Tomcat tomcat = new Tomcat();
    
            Server server = tomcat.getServer();
    
            Service service = server.findService("Tomcat");
    
            Connector connector = new Connector();
            connector.setPort(8081);
    
            StandardEngine standardEngine = new StandardEngine();
            standardEngine.setDefaultHost("127.0.0.1");
    
            StandardHost standardHost = new StandardHost();
            standardHost.setName("127.0.0.1");
    
            String contextPath = "";
            StandardContext standardContext = new StandardContext();
            standardContext.setPath(contextPath);
            standardContext.addLifecycleListener(new Tomcat.FixContextListener());
    
            standardHost.addChild(standardContext);
            standardEngine.addChild(standardHost);
    
            service.setContainer(standardEngine);
            service.addConnector(connector);
    
            tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet(applicationContext));
            standardContext.addServletMappingDecoded("/*","dispatcher");
    
            try {
                tomcat.start();
            }catch (LifecycleException e){
                e.printStackTrace();
            }
            
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    启动类这样在start传入
    在这里插入图片描述
    此时可以看到,我们真的启动了并且MVC正常工作。
    在这里插入图片描述

    在这里插入图片描述

    总结

    水完了~

  • 相关阅读:
    策略+枚举 优雅的消灭 if-else
    Web标准与前端开发| 青训营笔记
    你们看过《点燃我,温暖你》没有呀,里面比较火的那个爱心代码,今天小编用Python实现啦,这就是程序员的烂漫吗
    Jenkins数据迁移、备份与恢复-旧设备到新设备(简单教程)
    【超强图解Docker常见命令与实战】
    时域中的离散时间信号02—详解离散卷积
    Android 中的 本地广播LocalBroadcastManager
    buuctf web [极客大挑战 2019]LoveSQL
    国产化设备鲲鹏CentOS7上源码安装Python3.7
    JavaEE-网络编程套接字(UDP/TCP)
  • 原文地址:https://blog.csdn.net/FUTEROX/article/details/128163271