WebApplicationContext : org.springframework.web.context.ContextLoaderListener作用

如果您想要在自己所定义的Servlet类别中使用Spring的容器功能,则也可以使用 org.springframework.web.context.ContextLoaderListener,例如在web.xml中使用< listener>标签加以定义:

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


ContextLoaderListener预设会读取applicationContext.xml,您可以指定自己的定义档,只要在<context-param>中指定"contextConfigLocation"参数,例如:

...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans-config.xml,
→ /WEB-INF/demo-service.xml</param-value>
</context-param>
...


接着您可以在自定义的Servlet中使用 org.springframework.web.context.support.WebApplicationContextUtils,从 ServletContext中取得org.springframework.web.context.WebApplicationContext,例如:

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


WebApplicationContext实作了ApplicationContext介面,是Spring专为Servlet的Web应用程式设计的 ApplicationContext实作类别,在取得WebApplicationContext之后,您可以利用它来取得Bean定义档中定义的 Bean实例,例如:
Date date = (Date) ctx.getBean("dateBean");


在不支援Listener设定的容器上(例如Servlet 2.2以更早的版本),您可以使用org.springframework.web.context.ContextLoaderServlet来取代上面的ContextLoaderListener的设定,例如:

...
<servlet>
<servlet-name>contextLoader</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值