手机版
你好,游客 登录 注册
背景:
阅读新闻

Servlet 调用 Spring 容器的 service

[日期:2012-06-16] 来源:Linux社区  作者:defonds [字体: ]

自定义(继承自 Javax.servlet.http.HttpServlet)的 Servlet 如何像 Struts1/2 中那样调用 Spring 容器的 service 呢?

如同 Struts1/2 的配置一样,Spring 在 web.xml 中的配置及其 application*.xml 配置不变:

web.xml 中:

  1. <listener>  
  2.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  3. </listener>  

 

  1. <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>/WEB-INF/applicationContext*.xml</param-value>  
  4. </context-param>  

applicationContext-service.xml 中:

  1. <bean id="operationService"  
  2.     class="com.defonds.cds.service.operation.impl.OperationServiceImpl" scope="singleton">  
  3. </bean>  

如同一般的 Servlet 的配置一样,Servlet 在 web.xml 中的配置不变:

  1. <servlet>  
  2.     <servlet-name>downloadServlet</servlet-name>  
  3.     <servlet-class>com.defonds.cds.common.ArcSyncDownloadServlet</servlet-class>  
  4. </servlet>      
  5. <servlet-mapping>  
  6.     <servlet-name>downloadServlet</servlet-name>  
  7.     <url-pattern>/file</url-pattern>  
  8. </servlet-mapping>      

如同一般的 Struts1/2 的 action 一样注入 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 的 init 方法:

  1. public void init(ServletConfig config) throws ServletException {  
  2.     super.init(config);  
  3.     ServletContext servletContext = this.getServletContext();  
  4.     WebApplicationContext wac = null;   
  5.     wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
  6.     this.setOperationService((OperationService) wac.getBean("operationService"));//Spring 配置 中的 bean id   
  7. }     

这是一种办法。还有一种办法就是使用 Spring 将 Servlet 及其业务对象的依赖关系都管理起来,详细说明请参阅作者另一篇《使用 Spring 容器管理 Servlet》 见 http://www.linuxidc.com/Linux/2012-06/63008.htm。 

linux
相关资讯       Servlet  Spring 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款