歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Servlet 調用 Spring 容器的 service

Servlet 調用 Spring 容器的 service

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

自定義(繼承自 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. 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 的 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。

Copyright © Linux教程網 All Rights Reserved