ContextLoaderListener在Spring中的角色/目的? [英] Role/Purpose of ContextLoaderListener in Spring?

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

问题描述

我正在学习正在我的项目中使用的 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.



但我无法理解我在内部初始化 WebApplicationContext ContextLoaderListener 所取得的成就?

根据我的理解 ContextLoaderListener 读取Spring配置文件(使用中的contextConfigLocation给出的值) web.xml ),解析它并加载该配置文件中定义的 singleton bean 。类似地,当我们想要加载 prototype bean 时,我们将使用相同的webapplication上下文来加载它。因此,我们使用 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 的另一个方便之处是它创造了它a WebApplicationContext WebApplicationContext 提供对 ServletContext 的访问权限< a href =http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/ServletContextAware.html#setServletContext%28javax.servlet.ServletContext%29> ServletContextAware bean和 getServletContext 方法。

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

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

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