打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
sevlet 加载spring配置

如果您想要在自己所定义的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>
...

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
spring在web.xml中和在struts中的不同配置 - gwt600的专栏 - C...
转:SpringMVC理解之一:应用上下文webApplicationContext
spring MVC3深入研究(2)
spring源码研究之IoC容器在web容器中初始化过程 - ljbal - JavaEy...
DispatcherServlet作用
Spring,Struts整合方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服