自定義的 Servlet(繼承自 javax.servlet.http.HttpServlet)要怎樣才能像 Struts1/2 的 Action 那樣,取得 Spring 容器裡的 service 呢?答案其實不複雜。
Spring 在 web.xml 中的配置與 application*.xml 都維持原樣,不需要任何特別處理。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<bean id="operationService"
class="com.defonds.cds.service.operation.impl.OperationServiceImpl"
scope="singleton">
</bean>
這部分與一般 Servlet 無異:
<servlet>
<servlet-name>downloadServlet</servlet-name>
<servlet-class>com.defonds.cds.common.ArcSyncDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downloadServlet</servlet-name>
<url-pattern>/file</url-pattern>
</servlet-mapping>
與 Struts Action 相同,先準備屬性與存取器:
private OperationService operationService = null;
public OperationService getOperationService() {
return operationService;
}
public void setOperationService(OperationService operationService) {
this.operationService = operationService;
}
需要用到時直接呼叫:
FileInfo fileInfo = this.getOperationService()
.getFileByFidAndSecret(Long.parseLong(fileId), secret);
關鍵僅在初始化階段向容器索取 bean,並透過 setter 注入:
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext servletContext = this.getServletContext();
WebApplicationContext wac =
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
this.setOperationService((OperationService) wac.getBean("operationService"));
}
這是一種可行的做法。另一種更徹底的方式,是讓 Spring 連 Servlet 與業務物件的依賴關係都一起接管,細節可參考作者另一篇《使用 Spring 容器管理 Servlet》。