java - Spring 中 ContextLoaderListener 的作用/目的?

标签 java spring web-applications

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

ContextLoaderListener的官方文档中它说要启动WebApplicationContext。关于WebApplicationContext JavaDocs 说:

Interface to provide configuration for a web application.


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

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

最佳答案

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

  1. ApplicationContext 的生命周期绑定(bind)到 ServletContext 的生命周期和

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

ContextLoaderListener 的另一个方便之处是它创建了一个WebApplicationContext 并通过ServletContextAware 提供对ServletContext 的访问。 bean 和 getServletContext 方法。

关于java - Spring 中 ContextLoaderListener 的作用/目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11815339/

相关文章:

java - MULE ESB 中的 REST 调用

java - 如何解决Maven对MongoDB的依赖

java - 验证 Spring Web 应用程序配置的最佳实践

sql - HQL 与 SQL/Hibernate netbeans HQL 编辑器

android - 将 Web 应用程序连接到 mysql 数据库

java - 如何在java中准备SOAP请求并调用Web服务

java - 在Eclipse中调试时,在返回之前可以查出返回值吗?

java - android 从 arraylist 在 recyclerview 中创建组

java - hibernate 5.2.17 : ORA-01797: this operator must be followed by ANY or ALL

java - Spring RestTemplate : How to repeatedly check Restful API Service?