ContextLoaderListener和Spring MVC中的DispatcherServlet加载内容的区别

本文解析了ContextLoaderListener与DispatcherServlet的区别,包括它们在Web容器启动时如何加载bean配置,以及各自负责的不同类型的bean配置管理。此外还介绍了DispatcherServlet如何通过配置初始化参数来覆盖默认配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://blog.youkuaiyun.com/py_xin/article/details/52052627
ContextLoaderListener和DispatcherServlet都会在Web容器启动的时候加载一下bean配置. 区别在于:

DispatcherServlet一般会加载MVC相关的bean配置管理(如: ViewResolver, Controller, MultipartResolver, ExceptionHandler, etc.)
ContextLoaderListener一般会加载整个Spring容器相关的bean配置管理(如: Log, Service, Dao, PropertiesLoader, DataSource Bean, etc.)
DispatcherServlet默认使用WebApplicationContext作为上下文.

DispatcherServlet也可以配置自己的初始化参数,覆盖默认配置:

参数

描述

contextClass

实现WebApplicationContext接口的类,当前的servlet用它来创建上下文。如果这个参数没有指定, 默认使用XmlWebApplicationContext。

contextConfigLocation

传给上下文实例(由contextClass指定)的字符串,用来指定上下文的位置。这个字符串可以被分成多个字符串(使用逗号作为分隔符) 来支持多个上下文(在多上下文的情况下,如果同一个bean被定义两次,后面一个优先)。
默认为/WEB-INF/[server-name]-servlet.xml

namespace

WebApplicationContext命名空间。默认值是[server-name]-servlet。

如下:

[xml] view plain copy

demo
org.springframework.web.servlet.DispatcherServlet
1

contextConfigLocation
classpath:spring-servlet-config.xml



demo
/

值得注意的是, DispatcherServlet的上下文仅仅是Spring MVC的上下文, 而ContextLoaderListener的上下文则对整个Spring都有效. 一般Spring web项目中同时会使用这两种上下文.

上下文创建完后会放在ServletContext对象中, 其中:

1) ContextLoaderListener加载的上下文放在ServletContext的key为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性中;

2) DispatcherServlet加载的上下文在每次请求时会放一份在request对象的key为WEB_APPLICATION_CONTEXT_ATTRIBUTE属性中.

因而两者的获取方式也不一样, 前者可以通过:

WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)或

WebApplicationContextUtils.getWebApplicationContext(servletContext)或

WebApplicationContextUtils.getWebApplicationContext(servletContext,attrname)方法来获取对应的applicationContext,

而后者则通过:

RequestContextUtils.getWebApplicationContext(request)或

WebApplicationContextUtils.getWebApplicationContext(servletContext,attrname)方法来获取对应的applicationContext.

(注: 对于ContextLoaderListener加载的上下文, attrname即上面提到的WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;

而对于DispatcherServlet中的上下文则为FrameworkServlet.class.getName() + “.CONTEXT.” + getServletName())

通过上下文所在的属性可以看出,如果通过WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)来试图获取DispatcherServlet加载的applicationContext时, 就会抛出”No WebApplicationContext found: no ContextLoaderListener registered?”的异常.

注:本文部分转载自网络, 其中大多数参考了ContextLoaderListener和Spring MVC中的DispatcherServlet学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值