WebApplicationContext
在Web应用中,我们会用到WebApplicationContext 用它来保存上下文信息
那么它set到ServletContext的过程是怎么样呢
1)通过WEB.XML中监听类
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
触发contextInitialized方法
再来看
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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!" ); } 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); } |
最后一行,又调用了createWebApplicationContext方法,我们再来看一下这个方法的代码:
1
2
3
4
5
6
7
8
|
protected WebApplicationContext createWebApplicationContext(ServletContext sc) { Class<?> contextClass = determineContextClass(sc); 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); } |
通过代码可知,在这里返回了一个ConfigurableWebApplicationContext,再来看一下contextLoader的initWebApplicationContext方法中最关键的代码:
1
|
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this .context); |
在这里把context存入servletContext中,所以以后要用到WebApplicationContext的时候可以从servletContext取出。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?