自定义Servlet使用Spring容器功能

来源:互联网 发布:云南用友软件 编辑:程序博客网 时间:2024/05/21 11:21

 如果想要在自己所定义的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-servlce.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应用程序设计的ApplicatioContext实现类,在取得 WebApplicationContext之后,可以利用它来取得Bean定义文件中定义的Bean实例,例如:

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

在不支持Listener设定的容器上(例如Servlet2.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>

原创粉丝点击