歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用 Spring 容器管理 Servlet

使用 Spring 容器管理 Servlet

日期:2017/3/1 10:19:39   编辑:Linux編程

Servlet 可否也能像 Struts1/2 的 action 那樣作為一個 javaBean 在 Spring 容器裡進行管理呢?答案是肯定的。

自定義(繼承自 javax.servlet.http.HttpServlet)的 Servlet 如何像 Struts1/2 中那樣調用 Spring 容器的 service 呢?《Servlet 調用 Spring 容器的 service》一文很好地解決了這個問題。美中不足的是,ArcSyncDownloadServlet 在得到其注入的 bean 時,需要顯式地寫出 bean 在 Spring 配置中的 id 才可以:

this.setOperationService((OperationService) wac.getBean("operationService"));//Spring 配置 中的 bean id

這樣子違背了 Spring 依賴注入的思想。那麼如何才可以不在代碼中顯式調用這個 bean id,而把 bean id 直接寫在配置文件中呢?

本文用一個項目中使用的例子介紹了將 Servlet 和業務對象的依賴關系使用 Spring 來管理,而不用再在 Servlet 中硬編碼要引用對象的名字。

仍然使用《Servlet 調用 Spring 容器的 service》一文中的例子。

與《Servlet 調用 Spring 容器的 service》的做法相反,web.xml 和 Spring 的 application*.xml 配置需要改變,而 Servlet 不需要做改變。

如同 Struts1/2 的配置一樣,Spring 在 web.xml 中的配置:

  1. <listener>
  2. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  3. </listener>
  4. <context-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>/WEB-INF/applicationContext*.xml</param-value>
  7. </context-param>
如同 Struts1/2 的配置一樣,Spring 在 applicationContext-service.xml 中定義我們的業務邏輯處理類:
  1. <bean id="operationService"
  2. class="com.defonds.cds.service.operation.impl.OperationServiceImpl" scope="singleton">
  3. </bean>

如同一般的 Struts1/2 的 action 一樣在我們的 Servlet 中注入 service:

  1. private OperationService operationService = null;
  2. public OperationService getOperationService() {
  3. return operationService;
  4. }
  5. public void setOperationService(OperationService operationService) {
  6. this.operationService = operationService;
  7. }

在 Servlet 中如同一般的 Struts1/2 的 action 一樣調用 service:

  1. FileInfo fileInfo = this.getOperationService().getFileByFidAndSecret(Long.parseLong(fileId), secret);

如同一般的 Servlet 我們的這個 Servlet 需要繼承 GenericServlet 或者 HttpServlet:

  1. public class ArcSyncDownloadServlet extends HttpServlet
Copyright © Linux教程網 All Rights Reserved