Spring 中 ContextLoaderListener 的作用/目的? [英] Role/Purpose of ContextLoaderListener in Spring?

查看:20
本文介绍了Spring 中 ContextLoaderListener 的作用/目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习在我的项目中使用的 Spring Framework.我在我的 web.xml 文件中找到了 ContextLoaderListener 条目.但无法弄清楚它究竟如何帮助开发人员?

I am learning Spring Framework which is being used in my project. I found the ContextLoaderListener entry in my web.xml file. But could not figure out how exactly it helps a developer?

ContextLoaderListener 表示要启动WebApplicationContext.关于 WebApplicationContext JavaDocs 说:

In the official documentation of ContextLoaderListener it says it is to start WebApplicationContext. Regarding WebApplicationContext JavaDocs say:

为 Web 应用程序提供配置的接口.

Interface to provide configuration for a web application.


但是我无法理解我使用 ContextLoaderListener 实现了什么,它在内部初始化了 WebApplicationContext ?


But I am not able to understand what I am achieving with ContextLoaderListener which internally initializes the WebApplicationContext ?

根据我的理解ContextLoaderListener 读取 Spring 配置文件(根据 web.xml 中的 contextConfigLocation 给出的值),解析它并加载在该配置文件中定义的 singleton bean.同样,当我们想要加载 prototype bean 时,我们将使用相同的 webapplication context 来加载它.因此,我们使用 ContextLoaderListener 初始化 web 应用程序,以便我们提前读取/解析/验证配置文件,并且每当我们想要注入依赖项时,我们都可以立即进行,没有任何延迟.这种理解正确吗?

As per my understanding, ContextLoaderListener reads the Spring configuration file (with value given against contextConfigLocation in web.xml), parses it and loads the singleton bean defined in that config file. Similarly when we want to load prototype bean, we will use same webapplication context to load it. So we initialize the webapplication with ContextLoaderListener so that we read/parse/validate the config file in advance and whenever we wan to inject dependency we can straightaway do it without any delay. Is this understanding correct?

推荐答案

你的理解是正确的.ApplicationContext 是 Spring bean 所在的位置.ContextLoaderListener 的目的有两个:

Your understanding is correct. The ApplicationContext is where your Spring beans live. The purpose of the ContextLoaderListener is two-fold:

  1. ApplicationContext的生​​命周期与ServletContext

自动创建 ApplicationContext,因此您不必编写显式代码来创建它 - 这是一个方便的功能.

to automate the creation of the ApplicationContext, so you don't have to write explicit code to do create it - it's a convenience function.

ContextLoaderListener 的另一个方便之处是它创建了一个 WebApplicationContext 并通过 ServletContextAware bean 和 getServletContext 方法.

Another convenient thing about the ContextLoaderListener is that it creates a WebApplicationContext and provides access to the ServletContext via ServletContextAware beans and the getServletContext method.

这篇关于Spring 中 ContextLoaderListener 的作用/目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆