若是您想要在本身所定義的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>
...web