Servlet 调用 Spring 容器的 service

195 篇文章 1 订阅
   自定义(继承自 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. }    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值