如果你想要在自己定义的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.contextContextLoaderServlet代替org.springframework.web.context.ContextLoaderListener
的设定