使用 Spring 容器管理 Servlet


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.   
  6. public void setOperationService(OperationService operationService) {  
  7.     this.operationService = operationService;  
  8. }  

在 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  
  • 1
  • 2
  • 3
  • 下一页

相关内容