您的位置:首页 > 编程语言 > Java开发

org.springframework.web.context.ContextLoaderListener的作用

2013-09-06 10:43 477 查看
如果你想要在自己定义的servlet类别中使用spring的容器功能,则也可以使用org.springframework.web.context.ContextLoaderListener,

例如在web.xml使用 <listener>标签;来定义:

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

ContextLoaderListener会预读在web.xml中applicationContext.xml,不写任何参数配置信息,默认的路径是”/WEB-INF/applicationContext.xml,

你可以制定自己定义的文档,只要在<context-param>中指定"contextConfigLocation"参数,例如:

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

classpath:applicationContext.xml,/WEB-INF/httpinvoker-servlet.xml

</param-value>

</context-param>

接着你可以在自定义的servlet中使用:

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

WebApplicationContext实作了applicationContext的介面 ,是spring专门为servlet web应用程序设计的applicationContext实作类别,

在取得WebApplicationContext后,你可以利用它来取得Bean定文档的bean实例,例如:

Date date = (Date)getBean("dateBean");

在不支持listener的容器上你可以使用org.springframework.web.context.ContextLoaderServlet代替org.springframework.web.context.ContextLoaderListener

的设定

在spring3.0之后就将ContextLoaderServlet给删除了。

下面是讲解web.xml配置是ContextLoaderListener和DispatcherServlet的区别:

- ContextLoaderListener是在我们的web容器启动的时候启动的,默认会加载/WEB-INF/下面的applicationContext.xml文件。并创建一个WebApplicationContext容器。

- DispatcherServlet是在我们第一次访问我们的应用的时候创建的。这时候它默认会将配置在/WEB-INF下面的<servlet-name>-servlet.xml配置文件,然后也创建一个WebApplicationContext。这个WebApplicationContext将之前ContextLoaderListener创建的容器作为父容器,因此在父容器中配置的所有Bean都能够被注入到子容器中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐