Servlet容器初始化IOC容器

【ESP32 S3 开发】基于I2S协议驱动INMP441数字麦克风 实现语音采集 注意INMP441的 L/R接地之后才稳定输出数据 否则一直都是0WAV格式说明这里主要是想说wav文件重要的就是生成一个wavhead来标识它是一个wave文件,wave文件的data chunk 中的data部分还是PCM编码格式的数据,直接从I2S读进去就可以,不需要压缩。wav文件的头一般由4个chunk组成。 以16bit深度为例,代码如下。其他深度可以根据注释自行计算。 I2S -> DAC i2s_read()函数,向flash中划分的一个buff当中读入byte数组。以16bit深度为例,一 阅读详情

Servlet容器初始化IOC容器

<!-- ServletContext参数,配置Ioc容器的xml文件名 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
<!-- 初始化Ioc容器的监听器(重点就是这个监听器)-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

看下这个监听器:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
 
    public ContextLoaderListener() {
    }
    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }
    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }
 
    public void contextDestroyed(ServletContextEvent event) {
        closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
 
}

这个监听器首先实现了ServletContextListener,所以会在Servlet容器初始化和销毁的时候分别调用contextInitialized( )与contextDestroyed( )方法。

注意这里的带参构造方法 ContextLoaderListener(WebApplicationContext context)是调用了父类ContextLoader的构造方法,并传参进去。

而ContextLoader的主要作用就是初始化Ioc容器,下面我们来看看ContextLoader这个类

 

public class ContextLoader {
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";//ServletContext上下文参数
private WebApplicationContext context;
public ContextLoader(WebApplicationContext context) {
        this.context = context;
    }
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        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!");
        }//不能初始化Ioc容器,因为已经有一个根Application上下文,检查在web.xml中是否有多个ContextLoader
 
        Log logger = LogFactory.getLog(ContextLoader.class);
        servletContext.log("Initializing Spring root WebApplicationContext");
        if (logger.isInfoEnabled()) {
            logger.info("Root WebApplicationContext: initialization started");
        }//开始初始化WebApplicationContext
        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()) {//Ioc容器并未初始化,所以暂时不能提供服务
                    // 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) {//设置父applicationContext
                        // 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;
        }
    }

 

这里是总过程的描述:

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
        Class<?> contextClass = determineContextClass(sc);//获取context是由那个类定义的
        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {//判断是否为同一个类,或是子类
            throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
                    "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
        }
        return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

 

通过determineContextClass( )知道了实例化IOC容器方式,然后用这个方式,再通过反射机制实例化容器,即实例化webApplicationContext。

protected Class<?> determineContextClass(ServletContext servletContext) {
        String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);//该属性为"ContextClass"
        if (contextClassName != null) {
            try {
                return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
            }
            catch (ClassNotFoundException ex) {
                throw new ApplicationContextException(
                        "Failed to load custom context class [" + contextClassName + "]", ex);
            }
        }
        else {
            contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
            try {
                return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
            }
            catch (ClassNotFoundException ex) {
                throw new ApplicationContextException(
                        "Failed to load default context class [" + contextClassName + "]", ex);
            }
        }
    }

因为实例化Ioc容器的方式有几种,而这个方法是判定需要实例化那种类来实例化当前Web容器的Spring Ioc根容器。要判定需要实例化哪种类来实例化当前web容器的Spring根容器,如果我们设置了名称为“contextClass”的context-param,则取我们设置的类,该类应当实现ConfigurableWebApplicationContext接口或继承自实现了该接口的子类(如XmlWebApplicationContext、GroovyWebApplicationContext和AnnotationConfigWebApplicationContext),通常我们都不会设置,Spring会默认取与ContextLoader同目录下的ContextLoader.properties中记录的类名作为根容器的类型(默认是org.springframework.web.context.support.XmlWebApplicationContext);
 

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
        if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
            // The application context id is still set to its original default value
            // -> assign a more useful id based on available information
            String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
            if (idParam != null) {
                wac.setId(idParam);
            }
            else {
                // Generate default id...
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }
 
        wac.setServletContext(sc);
        String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
        if (configLocationParam != null) {
            wac.setConfigLocation(configLocationParam);
        }
 
        // The wac environment's #initPropertySources will be called in any case when the context
        // is refreshed; do it eagerly here to ensure servlet property sources are in place for
        // use in any post-processing or initialization that occurs below prior to #refresh
        ConfigurableEnvironment env = wac.getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {
            ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
        }
 
        customizeContext(sc, wac);
        wac.refresh();

}

虽然实例化了IOC容器,但是并未完成IOC容器的初始化,还不能提供服务。该方法的逻辑主要有一下几点:设置一个contextId(从contextId这个param获取,如果没有则默认是WebApplicationContext的类名 + “:” + servlet context的路径);设置配置位置(从contextConfigLocation 这个param获取,如果未配置,则默认是/WEB-INF/applicationContext.xml,在XmlWebApplicationContext中可以看出);自定义该congtext;调用该Context的refresh()方法。
 

上面描述了WebApplicationContext的构造,默认还是使用反射的方式构建XmlWebApplicationContext实例

 

public void closeWebApplicationContext(ServletContext servletContext) {
        servletContext.log("Closing Spring root WebApplicationContext");
        try {
            if (this.context instanceof ConfigurableWebApplicationContext) {
                ((ConfigurableWebApplicationContext) this.context).close();
            }
        }
        finally {
            ClassLoader ccl = Thread.currentThread().getContextClassLoader();
            if (ccl == ContextLoader.class.getClassLoader()) {
                currentContext = null;
            }
            else if (ccl != null) {
                currentContextPerThread.remove(ccl);
            }
            servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (this.parentContextRef != null) {
                this.parentContextRef.release();
            }
        }
    }

该方法完成了对Ioc容器的销毁。

PS:webApplicationContext实现了ApplicationContext接口的子类。是专门为WEB应用准备的。

1. 它允许从相对于Web根目录的路径中加载配置文件完成初始化工作。从WebApplicationContext中可以获取ServletContext引用,整个Web应用上下文对象将作为属性放置在ServletContext中,以便Web应用环境可以访问Spring上下文。 
2.WebApplicationContext还为Bean提供了三个新的作用域,request、session和globalsession。 
其中两个参数HttpServletRequest:服务器从客户端拿去数据 
HttpServletResponse:服务器向前台传送数据



原文:https://blog.youkuaiyun.com/Wayne_y/article/details/79778207
 

YOLOv11改进策略【模型轻量化】| 使用 MoblieOne 模块,引入结构重参数化,提高模型检测效率 本文记录的是基于MobileOne的YOLOv11骨干网络改进方法研究。MobileOne的基础模块通过重参数化,。在将其替换YOLOv11的骨干网络后,实现模型轻量化。 阅读详情

相关推荐

排列显示阿拉伯语、数字及英文时的处理方法

这段时间参与开发沙特阿拉伯的网站模板,模板使用的语言是阿拉伯语,其显示顺序为从右到左,而中文、数字及英文的显示顺序为从左到右 ,所以当遇到一行文字内既有阿拉伯语又有数字和英文时会出现语序混乱的问题,如 期待显示的文案为: 按顺序写入,对应的代码如以下,其中currency_pay为变量,值为356SAR <span>الدفع الفعلي:{{currency_pay}}</span> 显示为 الدفع الفعلي : 356SAR 金额356和货币符号SAR分开了,这样显

llq886的博客 5805

Servlet容器初始化Spring Ioc容器

&lt;!-- ServletContext参数,配置Ioc容器的xml文件名 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value...

Wayne_y的博客 871

ATAC-seq数据分析流程学习记录及总结

记录ATAC-seq数据分析流程,主要是参考健明老师的教程以及网上各种学习资源进行总结,网址在下面。

ACGTexplorer的博客 3754

如何在一个网站初始化的servlet中使用spring容器中的bean

之前遇到一个需求,场景是这样的,在一个WEB应用经常有一些数据需要在应用加载完成后就马上进行处理,比如把数据从数据库读取出来然后放到全局上下文供所有用户使用。 一般来说,我们会使用这样一种方式来实现: 写一个InitServlet,在web.xml配置1,这样就能在应用启动时立刻初始化 上面提到的这个servlet要实现的功能: 把数据从数据库读取出来然后放到全局上下文供所

wandrong的专栏 2480

电流镜设计实战:从基础到高级技巧(附常见问题解决方案)

本文从工程实战角度,系统讲解了电流镜设计从基础原理到高级技巧的全过程。深入剖析了匹配精度、输出阻抗等核心矛盾,并详细介绍了共源共栅(Cascode)结构如何平衡电压裕度与输出阻抗。文章还重点探讨了工艺偏差、版图应力效应等实战中的“隐形杀手”,并提供了常见问题的解决方案与调试技巧,旨在帮助工程师设计出鲁棒性更强的模拟电路。

blockchain9miner的博客 731

PINN——加入物理约束的神经网络

【摘要】 基于物理信息的神经网络(Physics-informed Neural Network, 简称PINN),是一类用于解决有监督学习任务的神经网络,它不仅能够像传统神经网络一样学习到训练数据样本的分布规律,而且能够学习到数学方程描述的物理定律。与纯数据驱动的神经网络学习相比,PINN在训练过程中施加了物理信息约束,因而能用更少的数据样本学习到更具泛化能力的模型。本文主要解析这种神经网络以...

qq_39444290的博客 4584

Spring MVC 初始化源码(1)—ContextLoaderListener监听器与父上下文容器的初始化

基于最新Spring 5.x,详细介绍了Spring MVC 初始化流程的源码,主要包括ContextLoaderListener与根上下文容器的初始化流程的源码,以及web.xml文件加载流程。

终生学习践行者 6293

Origin 2025b中文版安装全指南:避开乱码、水印与崩溃陷阱

Origin作为科研绘图领域的事实标准,其2025b版本首次官方支持简体中文UI,但安装远非‘下一步’即可完成。核心在于理解软件本体、语言包、许可证服务与系统区域设置四者间的耦合关系——尤其Windows非Unicode程序语言必须设为‘中文(简体,中国)’,否则必然触发坐标轴乱码、PDF文字方块等典型故障;而AI辅助拟合、内置Python 3.11等新特性,又依赖正确的字体链(如SimSun)与注册表强制加载(UILanguage=zh-CN)才能稳定启用。该版本广泛应用于材料科学、电化学、XRD/SEM

weixin_42548874的博客 1408

RequestContextHolder简析

在Web开发中,service层或者某个工具类中需要获取到HttpServletRequest对象还是比较常见的。一种方式是将HttpServletRequest作为方法的参数从controller层一直放下传递,不过这种有点费劲,且做起来不是优雅;还有另一种则是RequestContextHolder,直接在需要用的地方使用如下方式取HttpServletRequest即可,使用代码如下: ...

hnhygkx的博客 2328

IGBT模块封装中的银烧结技术:为什么特斯拉和比亚迪都在用这种黑科技?

本文深入解析了IGBT模块封装中的银烧结技术,揭示了其作为功率半导体封装工艺关键升级的原因。该技术通过低温烧结形成高熔点、高导热导电的银连接层,显著提升了模块的功率循环寿命、散热能力和高温工作稳定性,这正是特斯拉、比亚迪等行业巨头采用此项黑科技以释放电动汽车电驱系统极致性能的核心所在。

yhn4567890的博客 833

最全面的行人重识别数据集汇总

汇总了一些REID的数据集,几乎涵盖了所有的数据集。如果有缺少的欢迎留言补充。我将能下载到的数据集放在了网盘里,链接如下:链接:https://pan.baidu.com/s/1hQ4PKvtAhAvoZiXbcIu93w 提取码:o3iyQMUL iLIDS基于iLIDS MCTS的数据集,是一个在机场繁忙时候通过监控系统中多个摄像头收集到的数据集。几乎每个ID(identity)都有从两个无重叠(区域)的摄像头拍摄的四幅图像。该数据集具有严重遮挡和姿势差异的场景。

m0_47867638的博客 1万+

SpringMvc之RequestContextHolder

项目中除了Controller能够接收到请求对象HttpServletRequest和HttpServletResponse外,如果需要在service层使用以上请求和/或响应对象,如果直接从Controller传递过service层感觉太麻烦,而且耦合度太高;那么有什么方式可以优雅的解决该问题么? SpringMvc提供了RequestContextHolder对象!一、初识RequestCon...

jiangshubian的博客 2029

【Network Management】DCM模块唤醒网络是主动唤醒还是被动唤醒

DCM模块唤醒网络是主动唤醒还是被动唤醒

qq_36056498的博客 1539

IOC容器初始化之spring-servlet.xml容器(二)

Spring MVC容器的初始化序言Spring容器和Spring MVC容器的不同Spring MVC 容器的初始化 序言 在一个web应用中,我们经常会配置两个Spring容器,一个是applicationContext.xml;另一个是spring-servlet.xml applicationContext.xml的初始化是由ContextLoaderListener的initWebApp...

Dream2World,SayHi 261

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Servlet容器和IOC容器

Servlet如下,里面有一个studentService属性,通过springioc容器给studentService注入一个对象(配置监听器)。 public class QueryStudentByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; private IStude...

哈利路亚里路亚 1101

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

分析spring webmvc启动流程:serlvet注册、IoC容器创建、bean初始化、MVC的流程

serlvet注册 相关代码: 在servlet中,servlet及其子元素用来注册Servlet servlet-name 指定Servlet的名称,在同一个Web应用程序中,其名称必须是唯一的 servlet-class 指定Servlet类的完整限定名(包含包名) jsp-file 指定在Web应用程序中的JSP文件的完整路径,该路径以斜杠(/)开始 – – ...

weixin_43688599的博客 277

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

SpringMVC的IOC容器的初始化

SpringMVC的IOC容器的初始化 1.引导spring应用加载 首先,Servlet3.0的Web应用服务器中,例如Tomcat7或更高版本,服务器会在启动的时候在类路径下查找javax.servlet.ServletContainerInitializer接口的实现类(利用SPI原理),引导spring应用启动。执行实现WebApplicationInitializer类的onStartup方法 @HandlesTypes(WebApplicationInitializer.class) publi

yan_pan的博客 554

spring源码研究之IoC容器在web容器中初始化过程

前段时间在公司做了一个项目,项目用了spring框架实现,WEB容器是Tomct 5,虽然说把项目做完了,但是一直对spring的IoC容器在web容器如何启动和起作用的并不清楚。所以就抽时间看一下spring的源代码,借此了解它的原理。     我们知道,对于使用Spring的web应用,无须手动创建Spring容器,而是通过配置文件,声明式的创建Spring容器。因此在Web应用中创建Spr

qd_jz_gaoxiao 5741

springMVC初始化流程源码

1.ioc容器初始化过程: 容器启动时加载web.xml ContextLoaderListener继承了ServletContextListener,并重写了contextInitialized(ServletContextEvent event)方法,web容器启动时ServletContextListener监听调用ContextLoaderListener contextInitialized()方法 contextInitialized初始化initWebApplicationC..

javavshadoop的博客 184

servlet容器_Spring Boot学习04嵌入式Servlet容器启动原理

注:看完这一篇再回头看上一篇就会理解了上一篇文章解释了嵌入式Servlet容器的默认配置和修改配置的原理,但其前提条件是创建嵌入式Servlet容器工厂。下面就进行debug解释嵌入式Servlet容器是怎么启动的。1、来到ServletWebServerFactoryConfiguration类给组件TomcatServletWebServerFactory打上断点。再来到TomcatServl...

weixin_39608479的博客 67

Spring源码学习:SpringMVC(1)根容器初始化

​ Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。Servlet 是一个java 编写的程序,此程序基于http 协议,在服务端运行达到是按照servlet 规范编写的一个类。主要处理客户端的请求并将结果发送到客户端。​整个ContextLoaderListener类的启动过程到此就结束了,可以发现,创建是比较核心的一个步骤,主要工作就是为了创建根IoC容器。

small_kai的博客 1049

SpringMVC 中的DispatcherServlet生命周期是否受Spring IOC 容器管理

的生命周期主要由 Servlet 容器管理,但在其初始化过程中会与 Spring IoC 容器进行交互,以加载和配置 Spring MVC 相关的组件和 Bean。是 Spring MVC 的入口点,负责协调 Spring MVC 的各个组件来处理 HTTP 请求。

RodJohnsonDoctor的专栏 602

自我分析-Spring IOC在Web应用的启动和销毁

分析Spring IOC在Web应用的启动和销毁过程

哆啦咪^Pluser 4435

【Spring】DispatcherServlet的启动和初始化

使用过SpringMVC的都知道DispatcherServlet,下面介绍下该Servlet的启动与初始化。作为Servlet,DispatcherServlet的启动与Serlvet的启动过程是相联系的。在Serlvet的初始化过程程中,Serlvet的init方法会被调用,以进行初始化。DispatcherServlet的基类HttpServletBean中的这个初始化过程源码如下:

qq4165498的博客 1280

JavaEE学习笔记 04——Spring webmvc启动流程:serlvet注册、IoC容器创建、bean初始化、MVC的流程

目录一、项目目录结构二、serlvet注册、IoC容器创建二、bean初始化三、MVC的流程 一、项目目录结构 二、serlvet注册、IoC容器创建 将servlet注册为controller,我分为studentController和teacherController。 由原来的HttpServletRequest、HttpServletResponse 修改为@RequestBody ...

CRT本人的博客 315

SpringMVC初始化流程

web应用部署初始化流程 当一个Web应用部署到容器内时(eg.tomcat),在Web应用开始响应执行用户请求前,以下步骤会被依次执行: 部署描述文件中(eg.tomcat的web.xml)由&lt;listener&gt;元素标记的事件监听器会被创建和初始化 对于所有事件监听器,如果实现了ServletContextListener...

weixin_33790053的博客 170
上一篇: Spring积累
下一篇: Mybatis plus 高级
Art&Code
博客等级 码龄7年 77粉丝 554原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值