广告
返回顶部
首页 > 资讯 > 后端开发 > Python >java Spring的启动原理详解
  • 678
分享到

java Spring的启动原理详解

2024-04-02 19:04:59 678人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录引入spring启动过程总结:总结引入 为什么突然说一下Spring启动原理呢,因为之前面试的时候,回答的那可谓是坑坑洼洼,前前后后,补补贴贴。。。 总而言之就是不行,再次看一下

引入

为什么突然说一下Spring启动原理呢,因为之前面试的时候,回答的那可谓是坑坑洼洼,前前后后,补补贴贴。。。

总而言之就是不行,再次看一下源码发掘一下。。。

Spring Boot还没有广泛到家家在用的时候,我们都还在书写繁琐的配置,什么WEB.xml、spring.xml、bean.xml等等。虽然现在很少,可以说几乎没有企业在去使用Spring的老一套,而会去使用Spring Boot约定大于配置来进行快速开发,但是,Spring的也要去学习,去挖掘,毕竟是我们Java程序员的基础呀。

spring的启动是建筑在servlet容器之上的,所有web工程的初始位置就是web.xml,它配置了servlet的上下文(context)和监听器(Listener)

web.xml

<!--上下文监听器,用于监听servlet的启动过程-->
    <listener>
        <description>ServletContextListener</description>
        <!--这里是自定义监听器,个性化定制项目启动提示-->
        <listener-class>com.trace.app.framework.listeners.ApplicationListener</listener-class>
    </listener>
    <!--dispatcherServlet的配置,这个servlet主要用于前端控制,这是springMVC的基础-->
    <servlet>
        <servlet-name>service_dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--spring资源上下文定义,在指定地址找到spring的xml配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/application_context.xml</param-value>
    </context-param>
    <!--spring的上下文监听器-->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!--Session监听器,Session作为公共资源存在上下文资源当中,这里也是自定义监听器-->
    <listener>
        <listener-class>
            com.trace.app.framework.listeners.MySessionListener
        </listener-class>
    </listener>

Spring启动过程

spring的上下文监听器

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/application_context.xml</param-value>
</context-param>

<listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
 </listener>

spring的启动其实就是ioc容器的启动过程,通过上述的第一段配置 <context-param> 是初始化上下文,然后通过后一段的的<listener>来加载配置文件,其中调用的spring包中的ContextLoaderListener这个上下文监听器,ContextLoaderListener是一个实现了ServletContextListener接口的监听器,他的父类是 ContextLoader,在启动项目时会触发contextInitialized上下文初始化方法。

public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
}

调用了父类ContextLoader的initWebApplicationContext(event.getServletContext());方法,很显然,这是对ApplicationContext的初始化方法,也就是到这里正是进入了springIOC的初始化。

接下来看一下initWebApplicationContext(event.getServletContext())的工作:

if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - " +
                    "check whether you have multiple ContextLoader* definitions in your web.xml!");
        }

        Log logger = LogFactory.getLog(ContextLoader.class);
        servletContext.log("Initializing Spring root WebApplicationContext");
        if (logger.isInfoEnabled()) {
            logger.info("Root WebApplicationContext: initialization started");
        }
        long startTime = System.currentTimeMillis();

        try {
            // Store context in local instance variable, to guarantee that
            // it is available on ServletContext shutdown.
            if (this.context == null) {
                this.context = createWebApplicationContext(servletContext);
            }
            if (this.context instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
                if (!cwac.isActive()) {
                    // The context has not yet been refreshed -> provide services such as
                    // setting the parent context, setting the application context id, etc
                    if (cwac.getParent() == null) {
                        // The context instance was injected without an explicit parent ->
                        // determine parent for root web application context, if any.
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    configureAndRefreshWebApplicationContext(cwac, servletContext);
                }
            }
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

            ClassLoader ccl = Thread.currentThread().getContextClassLoader();
            if (ccl == ContextLoader.class.getClassLoader()) {
                currentContext = this.context;
            }
            else if (ccl != null) {
                currentContextPerThread.put(ccl, this.context);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
            }
            if (logger.isInfoEnabled()) {
                long elapsedTime = System.currentTimeMillis() - startTime;
                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
            }

            return this.context;
        }
        catch (RuntimeException ex) {
            logger.error("Context initialization failed", ex);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
            throw ex;
        }
        catch (Error err) {
            logger.error("Context initialization failed", err);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
            throw err;
        }

总结:

创建WebApplicationContext。加载对应的spring配置文件中的Bean。将WebApplicationContext放入ServletContext(JAVA WEB的全局变量)中。

接下来,来到了configureAndRefreshWebApplicationContext()方法

作用:

就是用来加载spring配置文件中的Bean实例的。这个方法于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。

总结:

在这里插入图片描述

总结

首先对于一个web应用,需要部署到web容器中,web容器提供了一个全局的上下文环境,ServletContext,SpringIOC的宿主环境。

其次,在web容器启动时,触发容器初始化,web.xml中提供的有ContextLoaderListener监听器会监听这个事件,初始化方法contextInitialized被调用,初始化spring上下文
WebApplicationContext接口,实现类时XmlWebApplicationContext即SpringIOC容器,对应的Bean定义是有context-param标签定义指定,然后存储到ServletContext中,方便获取。

ContextLoaderListener监听初始化完成后,开始初始化web.xml中配置的Servlet,指DisapatchServlet前端控制器,用来匹配,转发,处理每个Servlet请求,DisaptchServlet初始化时会创建自己的IOC上下文,用来持有Spring mvc的相关bean。
首先会从之前初始化存储在ServletContext中的上下文左右parent上下文,再初始化自己的上下文,大概的工作就是初始化处理器映射、视图解析等。这个servlet自己持有的上下文默认实现类也是xmlWebApplicationContext。然后存储到ServletContext。每个Servlet拥有自己的上下文,也会共享parent的上下文。

到此这篇关于java Spring的启动原理详解的文章就介绍到这了,更多相关java Spring启动原理内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: java Spring的启动原理详解

本文链接: https://www.lsjlt.com/news/138010.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • java Spring的启动原理详解
    目录引入Spring启动过程总结:总结引入 为什么突然说一下Spring启动原理呢,因为之前面试的时候,回答的那可谓是坑坑洼洼,前前后后,补补贴贴。。。 总而言之就是不行,再次看一下...
    99+
    2022-11-13
  • Spring事务的开启原理详解
    目录@EnableTransactionManagement开启事务原理解析总结 在事务配置类上声明@EnableTransactionManagement注解开启事务 在事...
    99+
    2022-11-11
  • JAVA Spring Boot 自动配置实现原理详解
    目录引言主启动类的注解@SpringBootApplication1、@SpringBootConfiguration2、@ComponentScan3、@EnableAutoCon...
    99+
    2022-11-12
  • Springboot启动原理详细讲解
    主启动类方法: @SpringBootApplication public class MyJavaTestApplication { public static void ...
    99+
    2022-11-13
  • Java Spring之@Async原理案例详解
    目录前言一、如何使用@Async二、源码解读总结前言 用过Spring的人多多少少也都用过@Async注解,至于作用嘛,看注解名,大概能猜出来,就是在方法执行的时候进行异步执行。 一...
    99+
    2022-11-12
  • Spring Boot启动的原理是什么
    本文小编为大家详细介绍“Spring Boot启动的原理是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Boot启动的原理是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起...
    99+
    2022-10-19
  • SpringBoot内置tomcat启动原理详解
    前言 不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在spring...
    99+
    2022-11-12
  • SpringBoot应用jar包启动原理详解
    目录1、maven打包2、Jar包目录结构3、可执行Jar(JarLauncher)4、WarLauncher5、总结1、maven打包 Spring Boot项目的pom.xml文...
    99+
    2022-11-13
  • Spring Cloud Feign原理详解
    目录Feign的大体机制@EnableFeignClients 和 @FeignClient 注解registerDefaultConfiguration方法registerFeig...
    99+
    2022-11-12
  • Kotlin协程launch启动流程原理详解
    目录1.launch启动流程反编译后的Java代码2.协程是如何被启动的1.launch启动流程 已知协程的启动方式之一是Globalscope.launch,那么Globalsc...
    99+
    2022-12-08
    Kotlin协程launch启动流程 Kotlin launch启动流程
  • Java @Async注解导致spring启动失败解决方案详解
    目录前言一、异常表现,抛出内容1.1循环依赖的两个class1.2启动报错二、原因分析2.1主要原因2.2循环依赖放入二级缓存处逻辑2.3initializeBean生成的对象2.4...
    99+
    2022-11-12
  • Spring @Transactional工作原理详解
    本文将深入研究Spring的事务管理。主要介绍@Transactional在底层是如何工作的。之后的文章将介绍:propagation(事务传播)和isolation(隔离性)等属性的使用事务使用的陷阱有哪些以及如何避免JPA和事务管理很重...
    99+
    2023-05-30
  • SpringBoot 嵌入式web容器的启动原理详解
    目录SpringBoot应用启动run方法SpringApplication.java 中执行的代码ServletWebServerApplicationContext.java执行...
    99+
    2022-11-12
  • Java SpringBoot自动装配原理详解
    目录自动装配的含义springboot应用程序启动类总结自动装配的含义 在SpringBoot程序main方法中,添加@SpringBootApplication或者@EnableA...
    99+
    2022-11-12
  • Spring体系的各种启动流程详解
    目录基本组件基础流程Springframework1、容器类2、注解定义bean读取器3、BeanFactoryPostProcessor4、refreshSpringMVC1、配置...
    99+
    2022-11-11
  • Java实现JDK动态代理的原理详解
    目录概念案例静态代理JDK动态代理模式原理分析真相大白概念 代理:为控制A对象,而创建出新B对象,由B对象代替执行A对象所有操作,称之为代理。一个代理体系建立涉及到3个参与角色:真实...
    99+
    2022-11-13
  • Spring和Mybatis整合的原理详解
    目录前言简单猜想案例搭建通过扫描接口正式开始setBeanNamesetApplicationContextafterPropertiespostProcessBeanDefinit...
    99+
    2022-11-13
  • spring boot启动加载数据原理分析
    实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。创建实现接口 CommandLine...
    99+
    2023-05-31
    spring boot 启动
  • Springboot启动原理和自动配置原理解析
    目录启动原理SpringApplication1、初始化2、调用run方法自动配置原理放本地文件夹都快吃土了,准备清理文件夹,关于Springboot的! 启动原理 @SpringB...
    99+
    2023-05-17
    Springboot启动原理和自动配置 Springboot自动配置 Springboot启动
  • Spring的IOC原理详情
    目录1 IOC的理论背景2 什么是控制反转(IoC)3 IOC的别名:依赖注入(DI)4 IOC为我们带来了什么好处5 IOC容器的技术剖析6 IOC容器的一些产品7 使用IOC框架...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作