手写Springboot核心流程

news2024/10/5 16:26:28

目录

Springboot启动流程

核心代码

验证效果


Springboot启动流程

  1. 创建Spring容器, 扫描并启动
  2. 容器选择Tomcat/Jetty
  3. 创建DispatchServlet, 与spring容器绑定
  4. 将DispatchServlet添加到Tomcat
  5. 启动Tomcat

核心代码

1. 首先, 创建两个module

 2. maven依赖

springboot模块依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>9.0.60</version>
        </dependency>
    </dependencies>

user模块依赖

        <dependency>
            <groupId>org.example</groupId>
            <artifactId>springboot</artifactId>
            <version>1.0-SNAPSHOT</version>
<!--            <exclusions>
                <exclusion>
                    <artifactId>tomcat-embed-core</artifactId>
                    <groupId>org.apache.tomcat.embed</groupId>
                </exclusion>
            </exclusions>-->
        </dependency>
<!--        切换netty-->
<!--        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.43.v20210629</version>
        </dependency>-->

3. springboot核心配置类 

public class KkSpringApplication {

    /*
        1. 创建Spring容器
        2. 创建Tomcat
        3. 创建DispatchServlet, 与spring容器绑定
        4. 将DispatchServlet添加到Tomcat
        5. 启动Tomcat
     */
    public static void run(Class clazz) {
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();
        WebServer webServer = getWebServer(applicationContext);
        webServer.start(applicationContext);
    }

    private static WebServer getWebServer(AnnotationConfigWebApplicationContext applicationContext) {
        Map<String, WebServer> map = applicationContext.getBeansOfType(WebServer.class);
        if (map.isEmpty()) {
            throw new NullPointerException();
        }
        if (map.size() > 1) {
            throw new IllegalStateException();
        }
        return map.values().stream().findFirst().get();
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Configuration
@ComponentScan
@Import(KkImportSeclet.class)
public @interface KkSpringBootApplication {

}

4. Import自动配置类

public class KkImportSeclet implements DeferredImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 自动配置
        ServiceLoader<AutoConfiguration> loader = ServiceLoader.load(AutoConfiguration.class);
        List<String> list = new ArrayList<>();
        for (AutoConfiguration configuration : loader) {
            list.add(configuration.getClass().getName());
        }
        return list.toArray(new String[0]);
    }
}
@Configuration
public class WebServerAutoConfiguration implements AutoConfiguration{

    @Bean
    @ConditionalOnClass("org.apache.catalina.startup.Tomcat")
    public TomcatWebServer tomcatWebServer(){
        return new TomcatWebServer();
    }

    @Bean
    @ConditionalOnClass("org.eclipse.jetty.server.Server")
    public JettyWebServer jettyWebServer(){
        return new JettyWebServer();
    }
}

public interface AutoConfiguration {
}

 spi注入自动配置类. 资源目录创建文件

5. 条件注解

public class KkCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalOnClass.class.getName());
        String className = (String) annotationAttributes.get("value");
        try {
            context.getClassLoader().loadClass(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }

    }
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Conditional(KkCondition.class)
public @interface ConditionalOnClass {

    String value();
}

6. Tomcat启动类实现

public class TomcatWebServer implements WebServer{
    @Override
    public void start(AnnotationConfigWebApplicationContext applicationContext) {
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(8081);

        Engine engine = new StandardEngine();
        engine.setDefaultHost("localhost");

        Host host = new StandardHost();
        host.setName("localhost");

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(applicationContext));
        context.addServletMappingDecoded("/*", "dispatcher");
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
        System.out.println("启动Tomcat ... ");
    }
}

7. User模块使用自定义springboot组件

@KkSpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        KkSpringApplication.run(MyApplication.class);
    }
}

验证效果

1. 启动MyApplication

 2. 调test接口

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1385884.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

网络安全|GitHub 已成为恶意软件传播的严重污染源

Recorded Future 凸显了全球合法平台威胁的上升。 根据 Recorded Future最近 的一份报告&#xff0c;开发者平台GitHub最近已成为黑客用来托管和传播恶意软件的流行工具。 该平台为攻击者提供了将其行为伪装成合法网络流量的能力&#xff0c;这使得跟踪和确定攻击者的身份变得…

【漏洞复现】Sentinel Dashboard默认弱口令漏洞

Nx01 产品简介 Sentinel Dashboard是一个轻量级的开源控制台&#xff0c;提供机器发现以及健康情况管理、监控、规则管理和推送的功能。它还提供了详细的被保护资源的实际访问统计情况&#xff0c;以及为不同服务配置的限流规则。 Nx02 漏洞描述 Sentinel Dashboard存在默认弱…

当前页面一键回关

CSDN博客关注页面当前页面一键回关所有fans代码 f12打开控制台&#xff0c;输入以下代码 // 获取所有的button元素&#xff0c;根据它们的属性进行筛选 var buttons document.querySelectorAll("button[data-v-0947769e][data-ref^li_][data-id][classattention-btn]&qu…

11.云原生分布式数据库之TIDB

云原生专栏大纲 文章目录 为什么使用TIDB后端视角运维视角基础架构视角 TiDB Operator 简介软件版本要求部署tidbTIDB工具helm常用命令TIDB学习推荐资料 为什么使用TIDB 从后端视角、运维视角和基础架构视角来看&#xff0c;使用 TiDB 作为数据库系统可以获得分布式架构、高可…

肯尼斯·里科《C和指针》第6章 指针(3)

肯尼斯里科《C和指针》第6章 指针&#xff08;1&#xff09;-CSDN博客 肯尼斯里科《C和指针》第6章 指针&#xff08;2&#xff09;-CSDN博客 前置知识&#xff1a;左值右值 为了理解有些操作符存在的限制&#xff0c;必须理解左值(L-value)和右值(R-value)之间的区别。这两个…

LLM之LangChain(二)| LangChain中的Agent

在本文中&#xff0c;我们将讨论LangChain中的Agent及其各种类型。但在深入研究Agent之前&#xff0c;让我们先了解一下什么是LangChain和Agent。 一、什么是LangChain&#xff1f; LangChain是一种功能强大的自动化工具&#xff0c;可用于各种任务&#xff0c;它提供了可用于…

卸载Notepad++!事实已证明,它更牛逼……

本文系统全面的介绍了 Sublime Text&#xff0c;旨在成为最优秀的 Sublime Text 中文教程。 前言 Sublime Text 是一款跨平台代码编辑器&#xff08;Code Editor&#xff09;&#xff0c;从最初的 Sublime Text 1.0&#xff0c;到现在的 Sublime Text 3.0&#xff0c;Sublime …

突破界限:首个国产DeepSeek MoE的高效表现

前言 在人工智能技术的快速发展过程中&#xff0c;国产首个开源MoE&#xff08;Mixture of Experts&#xff09;大模型——DeepSeek MoE的推出&#xff0c;不仅标志着中国在全球AI领域的重大突破&#xff0c;而且在计算效率和模型性能上展现了显著的优势。这款160亿参数的模型…

医疗器械生物学评价系列标准

医疗器械生物学评价系列标准(GB/T 16886/ISO 10993)是保障医疗器械安全的基础标准&#xff0c;内容涵盖医疗器械生物学评价基本指导原则、各项生物学试验方法、样品制备方法、理化表征方法等&#xff0c;是医疗器械生物学试验、评价、技术审批的重要依据&#xff0c;是医疗器械…

计算机图形学作业:Cohen-Sutherland和Liang-Barsky 裁剪算法

参考书籍和资料&#xff1a; Liang-Barsky参考下面视频14.2.1 [14.2.1]--讲解经典的梁友栋-巴斯基算法。_哔哩哔哩_bilibili Cohen-Sutherland参考孔令德的计算机图形学实验及课程设计&#xff08;第二版&#xff09;&#xff0c;实验五直线段的裁剪 题目如下&#xff1a; …

R语言【文章复现】——集成式地绘制高分辨率的多样性分布图,对方法的检验和优化,以及处理思路的思考

参考文献 本文对一篇 2022 年发表在 New Phytologist 的绘图方法文章中的技术路线进行复现。 An integrated high-resolution mapping shows congruent biodiversity patterns of Fagales and Pinales Summary 文中,作者针对在全球尺度上绘制物种分布图提出了一种全新的方法…

大白菜U盘安装系统-戴尔电脑

1. 把U盘插入电脑&#xff0c;启动盘去大白菜官网找&#xff0c;镜像可以去微软官网下&#xff0c;想要专业版的网上找资源。 2. 重启电脑&#xff0c;等出现log之后狂按F12&#xff0c;进入BOSS模式。 3. 选择UEFI...也就是下面白色的&#xff0c;按下回车。 4. 选第一个 5.…

数据结构_C++语言描述_高教出版社

contents 前言一、绪论1.1 数据分析结构存储算法计算1.1.1 逻辑结构1.1.2 存储结构1.1.3 算法实现 1.2 数据类型1.3 算法方法 二、线性表2.1 线性表的逻辑结构2.2 线性表的存储结构2.2.1 顺序存储结构2.2.2 链式存储结构 2.3 线性表的操作算法2.3.1 顺序表的操作算法2.3.2 链表…

RK3568驱动指南|驱动基础进阶篇-进阶3 驱动代码使用Makefile的宏

瑞芯微RK3568芯片是一款定位中高端的通用型SOC&#xff0c;采用22nm制程工艺&#xff0c;搭载一颗四核Cortex-A55处理器和Mali G52 2EE 图形处理器。RK3568 支持4K 解码和 1080P 编码&#xff0c;支持SATA/PCIE/USB3.0 外围接口。RK3568内置独立NPU&#xff0c;可用于轻量级人工…

Nvidia Jetson AGX Orin使用CAN与底盘通信(ROS C++ 驱动)

文章目录 一、Nvidia Jetson AGX Orin使用CAN通信1.1 CAN使能配置修改GPIO口功能1.2 can收发测试 二、通过CAN协议编写CAN的SocketCan ROS1驱动程序2.1 通讯协议2.2 接收数据节点2.3 发送数据节点2.4 功能包配置 三、ROS2驱动程序 一、Nvidia Jetson AGX Orin使用CAN通信 参考…

linux手动安装 vscode-server

适用场景 很多时候&#xff0c;我们需要在本机&#xff08;比如windows&#xff09;通过remote ssh访问远程服务器&#xff08;一般是ubuntu&#xff09;&#xff0c;但经常出现 vscode 一直连不上远程服务器的情况&#xff0c;看一下 log&#xff1a; 这个log表示远程服务器…

【2023年收入最高的10种编程语言】

在过去的一年时间里&#xff08;2022 年 10 月 1 日到 2023 年 10 月 1 日&#xff09; &#xff0c;DevJobsScanner 分析了来自世界各地的超过 1000 万份开发工作机会&#xff0c;以了解市场以及最热门、薪酬最高的编程语言。值得注意的是&#xff0c;本项研究只关注了来自美国…

【Linux】网络诊断 traceroute命令详解

目录 一、traceroute概述 1.1 traceroute命令简介 1.2 命令格式 1.3 原理 1.4 命令功能 二、使用实例 实例1&#xff1a;traceroute 用法简单、最常用的用法 实例2&#xff1a;跳数设置 实例3&#xff1a;设置探测数据包数量 实例4&#xff1a;显示IP地址&#xff0c…

什么是SAMBA?如何配置?方法来了!

/bin/bash 目录 SAMBA SMB协议 SMB连接过程 samba主要有两个进程 Linux下搭建samba服务器实现文件共享 Linux客户端&#xff1a; Windows客户端&#xff1a; SAMBA samba是SMB文件共享协议的应用软件&#xff0c;可以让Linux系统和Windows系统之间相互共享资源。 在Lin…

3d模型素材亮度和对比度如何调整呢?

1、修改材质参数&#xff1a;打开3ds Max后&#xff0c;选择要调整亮度和对比度的3D模型素材。然后&#xff0c;进入材质编辑器&#xff0c;选择相应的材质球。在材质编辑器中&#xff0c;你可以调整材质的漫反射、反射和高光等参数&#xff0c;这些参数将影响模型的亮度和对比…