Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Servlet 如何取得 Spring 容器中的 Service

自定義的 Servlet(繼承自 javax.servlet.http.HttpServlet)要怎樣才能像 Struts1/2 的 Action 那樣,取得 Spring 容器裡的 service 呢?答案其實不複雜。

Spring 在 web.xml 中的配置與 application*.xml 都維持原樣,不需要任何特別處理。

web.xml 部分

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

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

applicationContext-service.xml 部分

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

Servlet 在 web.xml 中的註冊

這部分與一般 Servlet 無異:

<servlet>
    <servlet-name>downloadServlet</servlet-name>
    <servlet-class>com.defonds.cds.common.ArcSyncDownloadServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>downloadServlet</servlet-name>
    <url-pattern>/file</url-pattern>
</servlet-mapping>

注入與呼叫

與 Struts Action 相同,先準備屬性與存取器:

private OperationService operationService = null;

public OperationService getOperationService() {
    return operationService;
}

public void setOperationService(OperationService operationService) {
    this.operationService = operationService;
}

需要用到時直接呼叫:

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

唯一需要改動的地方:init 方法

關鍵僅在初始化階段向容器索取 bean,並透過 setter 注入:

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext servletContext = this.getServletContext();
    WebApplicationContext wac =
        WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    this.setOperationService((OperationService) wac.getBean("operationService"));
}

這是一種可行的做法。另一種更徹底的方式,是讓 Spring 連 Servlet 與業務物件的依賴關係都一起接管,細節可參考作者另一篇《使用 Spring 容器管理 Servlet》。

Copyright © Linux教程網 All Rights Reserved